gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:53:45 24 4
gpt4 key购买 nike

这是我到目前为止:

Dim bProcess = Process.GetProcessesByName("By").FirstOrDefault
If bProcess IsNot Nothing Then
SwitchToThisWindow(bProcess.MainWindowHandle, True)
Else
Process.Start("C:\Program Files\B\B.exe")
End If
它有两个问题。
  • 有人告诉我,不推荐使用 SwitchToThisWindow。
  • 如果应用程序 B 被最小化,从用户的角度来看,这个函数会默默地失败。

  • 那么这样做的正确方法是什么?

    最佳答案

    获取窗口句柄(hwnd),然后使用这个 user32.dll 函数:

    VB.net声明:

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

    C#声明:
    [DllImport("user32.dll")] public static extern int SetForegroundWindow(int hwnd) 

    一个考虑是如果窗口被最小化,这将不起作用,所以我编写了以下方法来处理这种情况。这是 C# 代码,将其迁移到 VB 应该相当简单。
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
    private static extern bool ShowWindow(IntPtr hWnd, ShowWindowEnum flags);

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern int SetForegroundWindow(IntPtr hwnd);

    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
    };

    public void BringMainWindowToFront(string processName)
    {
    // get the process
    Process bProcess = Process.GetProcessesByName(processName).FirstOrDefault();

    // check if the process is running
    if (bProcess != null)
    {
    // check if the window is hidden / minimized
    if (bProcess.MainWindowHandle == 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(bProcess.MainWindowHandle);
    }
    else
    {
    // the process is not running, so start it
    Process.Start(processName);
    }
    }

    使用该代码,就像设置适当的流程变量并调用 BringMainWindowToFront("processName"); 一样简单。

    关于.net - 将焦点切换到另一个应用程序的正确方法(在 .NET 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2315561/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com