Max
Max

Reputation: 33

How to prevent the current window from losing focus when clicking a system tray icon

I'm writing a C# Windows Forms app for Windows 10, similar to the system virtual keyboard. The app is topmost and it doesn't steal focus by overriding CreateParams and ShowWithoutActivation:

private const int WS_EX_NOACTIVATE = 0x08000000;

protected override CreateParams CreateParams
{
    get
    {
        CreateParams params = base.CreateParams;
        params.ExStyle |= WS_EX_NOACTIVATE;
        return (params);
    }
}

protected override bool ShowWithoutActivation
{
    get { return true; }
}

The app can be minimized by the user to the system tray. This doesn't change the focus. However, when the app is restored from system tray (by clicking the app icon) the current active window loses focus.

Is there a way to avoid this behavior and keep the active window (before the mouse click) focused?

The app is minimized and restored using:

this.Hide();  // minimize on close event
..
this.Show();  // restore on notify icon click event

There was a similar question on here, but it's rather dated:
Prevent system tray icon from stealing focus when clicked

Upvotes: 1

Views: 2182

Answers (1)

Max
Max

Reputation: 33

Here's a temporary solution until someone finds a proper one. It works by continuously reading and saving the window in focus inside the app's tray icon mouse move event. This saved window will be set to focus inside the the tray icon mouse down event:

[DllImport("user32.dll", ExactSpelling = true)]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

private void notifyIcon_MouseDown(object sender, MouseEventArgs e)
{
    if (lastActiveWin != IntPtr.Zero)
    {
        SetForegroundWindow(lastActiveWin);
    }
}

IntPtr lastActiveWin = IntPtr.Zero;
private void notifyIcon_MouseMove(object sender, MouseEventArgs e)
{
    lastActiveWin = GetForegroundWindow();
}

Upvotes: 1

Related Questions