I have a winform Application written in C#. This application should show Notifications on the Desktop that are non-interactable and should not gain focus. Now I've figured out how to spawn windows in the background (behind all other applications) and make them non-interactable. Despite them being disabled, every time I click on one, the Windows "DING" sound plays.
Is there a way to have a form Enabled = false;
without it giving the ding sound when trying to click on it?
Instead of having the form disabled, I also try to capture all the click events and prevent the focusing, but this has not worked so far.
Below is the code I used for creating the windows form.
using System.Runtime.InteropServices;
namespace Background_Notes;
public partial class Note : Form
{
[DllImport("user32.dll")]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
static readonly IntPtr HwndBottom = new IntPtr(1);
const UInt32 SwpNosize = 0x0001;
const UInt32 SwpNomove = 0x0002;
const UInt32 SwpNoactivate = 0x0010;
public Note()
{
InitializeComponent();
ShowInTaskbar = false;
FormBorderStyle = FormBorderStyle.None;
SetStyle(ControlStyles.Selectable, false);
TextBox t = new TextBox();
t.Width = 200;
t.Text = "This is a notification!";
Controls.Add(t);
Show();
SetWindowPos(Handle, HwndBottom, 0, 0, 0, 0, SwpNomove | SwpNosize | SwpNoactivate);
Enabled = false;
}
protected override bool ShowWithoutActivation => true;
}
CodePudding user response:
To make the window always inactive, apply WS_EX_NOACTIVATE to the extended window style.There is no need to disable the form.
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
if (DesignMode)
return cp;
const int WS_EX_NOACTIVATE = 0x8000000;
cp.ExStyle |= WS_EX_NOACTIVATE;
return cp;
}
}