I’m using a C# app to listen for a global combination of keys (ctrl+F9) that will bring a specific window to front.
This is the code I’m using to bring a window to front, it works only if fired by a Button event:
private void button3_Click(object sender, EventArgs e)
{
SetForegroundWindow(ptrActiveWindow.ToInt32());
ShowWindowAsync(ptrActiveWindow, SW_RESTORE);
}
For hooking, I’ve used a class taken from http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx, which is fully listed here:
Whenever I have a F9 KeyUp event after a CTRL KeyDown and before a CTRL KeyUp (CTRL is still pressed), I call my method:
private void restore(IntPtr hWnd)
{
IntPtr ptrCurrentActiveWindow = GetForegroundWindow(); //comment line
ShowWindowAsync(ptrCurrentActiveWindow, SW_MINIMIZE); //comment line
ShowWindowAsync(hWnd, SW_RESTORE);
SetFocus(hWnd);
SetForegroundWindow(hWnd.ToInt32());
}
This does nothing. My window is activated in the background (I can see it blinking in the taskbar), but does not get restored.
The only way I can move around this is to use the commented code: minimize the currently active window and afterwards restore the window I want to see.
All help is appreciated,
Thanks.
Global hotkey, working version:
private void Form1_Load(object sender, EventArgs e)
{
string atomName = Thread.CurrentThread.ManagedThreadId.ToString("X8") + this.GetType().FullName;
short HotkeyID = GlobalAddAtom(atomName);
if (!RegisterHotKey(this.Handle, HotkeyID, (uint)GlobalHotkeys.MOD_CONTROL, (uint)Keys.D5))
listBox.Items.Add("failed: " + "unable to register hotkey. Error: " + Marshal.GetLastWin32Error().ToString());
else
listBox.Items.Add("succeeded adding hotkey id"+(uint)Keys.D5);
}
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
if (m.Msg == WM_HOTKEY)
{
if ((short)m.WParam==HotkeyID)
listBox.Items.Add("Hotkey."+ (short)m.WParam);
}
base.WndProc(ref m);
}
Your problem is that you didn’t register a global hotkey but used a keyboard hook instead. Keyboard hooks are not designed to be used as global hotkeys.
Use the
RegisterHotKeyfunction instead.Check this example: http://www.pinvoke.net/default.aspx/user32.registerhotkey
Your immediate problem is that an application can’t put itself into the foreground whenever it likes. Because that’s annoying to the user. It can only do that during specific event. Like application startup or when handling a real global hotkey.