- 1 year ago
Alternative to TopMost with no focus on the taskbar
Comment
1 / 1
If you want to keep a window always on top of other windows but without stealing focus from the taskbar, you can achieve this by using the WS_EX_NOACTIVATE
extended window style in Windows. This style allows a window to be displayed on top without activating it.
Here's an example of how you can set the WS_EX_NOACTIVATE
style for a window in C# using WinForms:
csharpusing System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class MainForm : Form
{
private const int WS_EX_TOPMOST = 0x00000008;
private const int WS_EX_NOACTIVATE = 0x08000000;
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
public MainForm()
{
// Set the extended window style
int exStyle = GetWindowLong(this.Handle, -20);
SetWindowLong(this.Handle, -20, exStyle | WS_EX_TOPMOST | WS_EX_NOACTIVATE);
// Set other properties for the form
this.Text = "Always On Top";
this.Width = 300;
this.Height = 200;
}
static void Main()
{
Application.Run(new MainForm());
}
}
In this example, the WS_EX_NOACTIVATE
style is combined with the WS_EX_TOPMOST
style using bitwise OR. This allows the window to be displayed on top of other windows without activating it and without stealing focus from the taskbar.
Note that this approach uses Windows-specific functionality and may not work on non-Windows platforms.