In C#, how to activate the previously focused window?

I work eg. in Firefox, and my C#.NET app brings its window to the front. That's ok, but when I use SendToBack() to hide the form, it doesn't activate Firefox's window, so altough Firefox is in the foreground, I have to click into the window to be able to scroll, etc. How can I activate the previously focused window in C#?

i have tried these:

[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);

[DllImport("user32.dll")]
static extern bool AllowSetForegroundWindow(int dwProcessId);

[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

[...]

AllowSetForegroundWindow(System.Diagnostics.Process.GetCurrentProcess().Id);
SendToBack();
SetForegroundWindow(GetForegroundWindow());

I hoped that after sending my window back, the previous one will be returned by GetForegroundWindow, but it doesn't work.

Secondly, I've tried to override WndProc, and handle the WM_ACTIVATE message to get the previous window from lParam, but it doesn't work either if I use SetForegroundWindow() with this handle.

protected override void WndProc(ref Message msg) {
        if (msg.Msg == 0x0006) {
            prevWindow = msg.LParam;
        }
        base.WndProc(ref msg);
}

[...]

SetForegroundWindow(prevWindow);

did you try the SetActiveWindow function? Its separate from the SetForgroundWindow function, although it seems that you may need to use them both.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms646311%28v=vs.85%29.aspx

There is also a SetFocus function which sounds like it could work.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms646312%28v=vs.85%29.aspx

Update

To get the current Active Window, I would fire off the GetActiveWindow function before moving your application to the front of the stack, that way you have the handle for the window that was active before hand.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms646292%28v=vs.85%29.aspx

Another Update I did a bit more digging around on the site and came up with the following three links, which might work better. The keyboard input functions seem to be dependent on the Window you are trying to set being part of the calling threads message queue, which since we are dealing with two separate application threads, is likely to not be the case.

GetGUIThreadInfo Get the threads information, including active window

GUITHREADINFO The GUITHREADINFO structure

SwitchToThisWindow Another method of window changing

All of these are in the same method stack as the SetForegroundWindow method, which seems to make them more likely to do what you are attempting.


当您调用SetFocus()向前移动应用程序时,它将返回之前焦点所在的窗口的句柄。

链接地址: http://www.djcxy.com/p/55924.html

上一篇: 发布后无法打开Word文档(Office.Interop.Word)

下一篇: 在C#中,如何激活之前关注的窗口?