正确的方法(在.NET)将焦点切换到另一个应用程序 [英] Correct way (in .NET) to switch the focus to another application
本文介绍了正确的方法(在.NET)将焦点切换到另一个应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我到目前为止有:
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
它有两个问题。
It has two problems.
- 有人告诉我,SwitchToThisWindow是depricated。
- 如果应用程序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 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();
这篇关于正确的方法(在.NET)将焦点切换到另一个应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文