将焦点切换到另一个应用程序的正确方法(在 .NET 中) [英] Correct way (in .NET) to switch the focus to another application

查看:39
本文介绍了将焦点切换到另一个应用程序的正确方法(在 .NET 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前所拥有的:

Dim bProcess = Process.GetProcessesByName("By").FirstOrDefault
If bProcess IsNot Nothing Then
    SwitchToThisWindow(bProcess.MainWindowHandle, True)
Else
    Process.Start("C:Program FilesBB.exe")
End If

它有两个问题.

  1. 有人告诉我 SwitchToThisWindow 已被弃用.
  2. 如果应用程序 B 被最小化,则从用户的角度来看,此功能会默默地失败.

那么正确的做法是什么?

So what's the right way to do this?

推荐答案

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

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

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 应该相当简单.

One consideration is that this will not work if the window is minimized, so I've written the following method which also handles this case. Here is the C# code, it should be fairly straight forward to migrate this to 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");

Using that code, it would be as simple as setting the appropriate process variables and calling BringMainWindowToFront("processName");

这篇关于将焦点切换到另一个应用程序的正确方法(在 .NET 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆