设置外部应用程序焦点

在VB.NET中,您可以使用焦点设置焦点到外部应用程序

AppActivate("Windows Name") 

要么

 AppActivate(processID As Integer) 

现在这可以正常工作,例如:

 Dim intNotePad As Integer = Shell("C:\WINNT\Notepad.exe", AppWinStyle.MinimizedNoFocus) AppActivate(intNotePad) 

但当我这样做时:

 For Each theprocess As Process In processlist If InStr(theprocess.ProcessName, "DWG") Then strProcessList += String.Format("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id) + vbCrLf AppActivate(theprocess.ID) End If Next 

然后它找不到窗口,即使它是打开的,即使它使用窗口标题找到窗口。

但我需要按进程ID。

我怎样才能做到这一点?

我需要它专注于Windows安装程序安装项目中的第三方安装程序。

我不知道为什么你没有达到正确的结果。 通常,在将焦点设置到其他应用程序时,我从来没有过多运气AppActivate (至少有不同程度的成功)。 试试这个:

将此类添加到相同的模块/对象/您的代码:

 Public NotInheritable Class Win32Helper  _ Public Shared Function _ SetForegroundWindow(ByVal handle As IntPtr) As Boolean ' Leave function empty End Function  _ Public Shared Function ShowWindow(ByVal handle As IntPtr, _ ByVal nCmd As Int32) As Boolean ' Leave function empty End Function End Class 

然后在您的代码中,而不是AppActivate ,执行以下操作:

 Dim appHandle As intPtr appHandle = theprocess.MainWindowHandle 'theprocess is naturally your process object Dim Win32Help As New Win32Helper Win32Helper.SetForegroundWindow(appHandle) 

试试这些Win32函数:

 Declare Sub SwitchToThisWindow Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal fAltTab As Boolean) Declare Function SetActiveWindow Lib "user32.dll" (ByVal hwnd As IntPtr) As IntPtr 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 End Enum 

使用Process.MainWindowHandle获取句柄。 这适用于大多数应用程序,但不是所有应用程序。