且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正确的方法(在.NET)将焦点切换到另一个应用程序

更新时间:2023-11-22 16:57:16

获取窗口句柄(HWND),然后用这个user32.dll中的功能:

Get the window handle (hwnd), and then use this user32.dll function:

VB.net声明:

Declare Function SetActiveWindow Lib "user32.dll" (ByVal hwnd As Integer) As Integer 

C#声明:

C# declaration:

[DllImport("user32.dll")] public static extern int SetActiveWindow(int hwnd) 

我的VB.net是很生疏,这里是C#code,但:

My VB.net is VERY rusty, here is the C# code though:

[System.Runtime.InteropServices.DllImport("user32.dll")]
[return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
static extern bool ShowWindow(IntPtr hWnd, ShowWindowEnum flags);
private enum ShowWindowEnum
{
    Hide = 0,
    ShowNormal = 1, ShowMinimized = 2, ShowMaximized = 3,
    Maximize = 3, ShowNormalNoActivate = 4, Show = 5,
    Minimize = 6, ShowMinNoActivate = 7, ShowNoActivate = 8,
    Restore = 9, ShowDefault = 10, ForceMinimized = 11
};

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SetForegroundWindow(IntPtr hwnd);
public void BringWindowToFront()
{
    string processName = "name";
    string processFilePath = @"C:\Program Files\B\B.exe";
    //get the process
    Process bProcess = Process.GetProcessesByName(processName).FirstOrDefault();
    //check if the process is nothing or not.
    if (bProcess != null)
    {
        //get the  hWnd of the process
        IntPtr hwnd = bProcess.MainWindowHandle;
        if (hwnd == IntPtr.Zero)
        {
            //the window is hidden so try to restore it before setting focus.
            ShowWindow(bProcess.Handle, ShowWindowEnum.Restore);
        }

        //set user the focus to the window
        SetForegroundWindow((int)bProcess.MainWindowHandle);
    }
    else
    {
        //tthe process is nothing, so start it
        Process.Start(processName);
    }
}

使用code,这将非常简单,如设置适当的工艺参数,并呼吁 BringWindowToFront();