I'm trying to get a handle to the foreground window in C#/Net 2.0/WinForms by calling the native GetForegroundWindow WinAPI function, in my app's form's constructor.
When I run the program directly from Windows Explorer or Total Commander, it correctly identifies the Windows Explorer or Total Commander window.
However, if I create a shortcut to my program on desktop and set a shortcut key for the shortcut (let's say Ctrl+Alt+X), when I'm running my program using the shortcut, the foreground window is identified as the "Shell_TrayWnd window" (Handle 0x00010064), and not the actual window. (Let's say I'm running Firefox on top, when I press Ctrl+Alt+X my program starts and says that the foreground window is not Firefox, as it should, it says it's the taskbar - Shell_TrayWnd.)
public MainForm()
{
this.InitializeComponent();
IntPtr handle = WinAPI.GetForegroundWindow();
this.Text = handle.ToString();
StringBuilder title = new StringBuilder(255);
if (WinAPI.GetWindowText(handle, title, 255) > 0)
{
this.Text += title.ToString();
}
}
How can I get the real foreground window? Should I (also) use other functions like GetWindow?
Thank you
Note that the task bar may be the real foreground window at the time you call GetForegroundWindow, simply because it's Explorer who's handling the shortcut press, and the task bar belongs to Explorer (Shell_TrayWnd is the window class of the task bar).
If you want to do something with the global active window, you may be better off by starting your application and letting it wait in the background. Then you can handle key presses while your application is running, so Explorer won't interfere.
Somehow, this reminds me of an article by Raymond Chen.