2009-12-17 88 views
1

在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安裝程序安裝項目中的第三方安裝程序的重點。

+0

爲什麼這個標籤爲「asp.net」? – AUSteve 2010-01-08 00:10:23

+0

請不要使用'InStr'。 'process.ProcessName.Contains(「DWG」)'是「正確的」.NET方法。 – Ryan 2012-06-06 03:23:28

回答

3

我不知道你爲什麼沒有達到正確的結果。一般來說,在將焦點設置到其他應用程序時,我從來沒有太多運氣與AppActivate(不同程度的成功,至少)。試試這個:

這個類添加到同一個模塊/對象/徘徊無論你的代碼是:

Public NotInheritable Class Win32Helper 
    <System.Runtime.InteropServices.DllImport("user32.dll", _ 
    EntryPoint:="SetForegroundWindow", _ 
    CallingConvention:=Runtime.InteropServices.CallingConvention.StdCall, _ 
    CharSet:=Runtime.InteropServices.CharSet.Unicode, SetLastError:=True)> _ 
    Public Shared Function _ 
    SetForegroundWindow(ByVal handle As IntPtr) As Boolean 
     ' Leave function empty 
    End Function 

    <System.Runtime.InteropServices.DllImport("user32.dll", _ 
    EntryPoint:="ShowWindow", _ 
    CallingConvention:=Runtime.InteropServices.CallingConvention.StdCall, _ 
    CharSet:=Runtime.InteropServices.CharSet.Unicode, SetLastError:=True)> _ 
    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) 
2

試試這些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得到處理。這適用於大多數應用程序,但不是全部。