2006-04-27
Ever found that you can't set the foreground window if you're not the current foreground thread? I was working on StartMenuEx and found that the contextMenuStrip won't close if the window it's being displayed on isn't the foreground window.
Friend Class SetForegroundWindowEx
Private Declare Function SetForegroundWindow Lib "user32.dll" (ByVal hWnd As IntPtr) As Boolean
Private Declare Function GetForegroundWindow Lib "user32.dll" () As IntPtr
Private Declare Function GetWindowThreadProcessId Lib "user32.dll" (ByVal hWnd As IntPtr, ByRef lpdwProcessId As Integer) As Integer
Private Declare Function GetCurrentThreadId Lib "kernel32.dll" () As Integer
Private Declare Function AttachThreadInput Lib "user32.dll" (ByVal idAttach As Integer, ByVal idAttachTo As Integer, ByVal fAttach As Boolean) As Boolean
Public Shared Sub SetForegroundWindowEx(ByVal hWnd As IntPtr)
Dim foregroundThreadID As Integer
Dim ourThreadID As Integer
foregroundThreadID = GetWindowThreadProcessId(GetForegroundWindow(), Nothing)
ourThreadID = GetCurrentThreadId
If Not (foregroundThreadID = ourThreadID) Then
AttachThreadInput(foregroundThreadID, ourThreadID, True) 'attach
SetForegroundWindow(hWnd) 'set foreground window
AttachThreadInput(foregroundThreadID, ourThreadID, False) 'detach
Else
SetForegroundWindow(hWnd)
End If
End Sub
End Class
peace
blog comments powered by
Disqus
3