这是我到目前为止有:
Dim bProcess = Process.GetProcessesByName("By").FirstOrDefault
If bProcess IsNot Nothing Then
SwitchToThisWindow(bProcess.MainWindowHandle, True)
Else
Process.Start("C:Program FilesBB.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 FilesBB.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();