How do I bring an unmanaged application window to front, and make it the active window for (simulated) user input

最后都变了- 提交于 2020-01-19 03:45:19

问题


I am assuming I need to use pinvoke but I am not sure which function calls are needed.

Detailed scenario. A legacy application will be running. I will have Handle for that application. I need to: a) bring that application to the top (in front of all other windows). b) Make it the active window.

Which windows function calls are needed?


回答1:


If you don't have a handle to the window, use this before :

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

Now assuming you have a handle to the application window :

[DllImport("user32.dll", SetLastError = true)]
static extern bool SetForegroundWindow(IntPtr hWnd);

This will make the taskbar flash if another window has keyboard focus.

If you want to force the window to come to the front, use ForceForegroundWindow (sample implementation).




回答2:


This has proved to be extremely reliable. The ShowWindowAsync function is specifically designed for windows created by a different thread. The SW_SHOWDEFAULT makes sure the window is restored prior to showing, then activating.

    [DllImport("user32.dll", SetLastError = true)]
    internal static extern bool ShowWindowAsync(IntPtr windowHandle, int nCmdShow);

    [DllImport("user32.dll", SetLastError = true)]
    internal static extern bool SetForegroundWindow(IntPtr windowHandle);

Then making the calls:

ShowWindowAsync(windowHandle, SW_SHOWDEFAULT);
ShowWindowAsync(windowHandle, SW_SHOW);
SetForegroundWindow(windowHandle);



回答3:


    [DllImport("user32.dll")]
    public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
    [DllImport("user32.dll")]
    public static extern bool SetForegroundWindow(IntPtr WindowHandle);
    public const int SW_RESTORE = 9;

ShowWindowAsync method is used to show the minimized application and SetForegroundWindow method is used to bring on front the back application.

you can use these methods as i used in my application to bring the skype infront of my application. on button click

private void FocusSkype()
    {
        Process[] objProcesses = System.Diagnostics.Process.GetProcessesByName("skype");
        if (objProcesses.Length > 0)
        {
            IntPtr hWnd = IntPtr.Zero;
            hWnd = objProcesses[0].MainWindowHandle;
            ShowWindowAsync(new HandleRef(null,hWnd), SW_RESTORE);
             SetForegroundWindow(objProcesses[0].MainWindowHandle);
        }
    }


来源:https://stackoverflow.com/questions/6228089/how-do-i-bring-an-unmanaged-application-window-to-front-and-make-it-the-active

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!