How do I check if a Window is in Focus? Like, I want to put in a Process Name, and see if its the Window in focus.
Printable View
How do I check if a Window is in Focus? Like, I want to put in a Process Name, and see if its the Window in focus.
Wouldn't your window be the one in focus then?
How would that make your window not the focused one?
You can use the GetForegroundWindow API to get the window that is currently in focus, but I'm not sure about your method of triggering your code to be run when not in focus - I think the RegisterHotKey API might be a better way of doing it because as I see it you are going to have to constantly check that GetAsyncKeyState function every second or so (which is never a good way of doing something).
Here's an example of how to declare the GetForegroundWindow API:
vb Code:
''' <summary> ''' Gets the Hwnd of the currently active window ''' </summary> <System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint:="GetForegroundWindow")> _ Public Shared Function GetForegroundWindow() As System.IntPtr End Function
and RegisterHotKey:
RegisterHotKey is a bit more involved than just calling a method though, you have to override the window message processing event for your form to capture the message that is sent when the hotkey is pressed, like so:vb Code:
'Constants Public Const WM_HOTKEY As Integer = &H312 Public Const MOD_ALT As Integer = 1 Public Const MOD_CONTROL As Integer = 2 Public Const VK_CONTROL As Integer = &H11 ''' <summary> ''' Registers a system wide hotkey ''' </summary> ''' <param name="hWnd">The Hwnd of the window that should receive a notification when the hotkey is pressed</param> ''' <param name="id">A unique ID for the hotkey</param> ''' <param name="fsModifiers">The keys that must be pressed when vk is pressed to trigger the hotkey</param> ''' <param name="vk">The key that must be pressed when the keys in fsModifiers are pressed to trigger the hotkey</param> Public Declare Function RegisterHotKey Lib "user32" Alias "RegisterHotKey" (ByVal hWnd As IntPtr, ByVal id As Integer, ByVal fsModifiers As UInteger, ByVal vk As UInteger) As Boolean ''' <summary> ''' Removes a system wide hotkey ''' </summary> ''' <param name="hWnd">The Hwnd of the window that the hotkey was registered against</param> ''' <param name="id">The ID of the hotkey to remove</param> Public Declare Function UnregisterHotKey Lib "user32" Alias "UnregisterHotKey" (ByVal hWnd As IntPtr, ByVal id As Integer) As Boolean
vb.net Code:
'<<< Override the message processing routine to capture the WM_HOTKEY message >>> Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) If m.Msg = WM_HOTKEY Then If m.WParam.ToString = "6003" Then '<-- change this number to match the ID you gave the hotkey when you called RegisterHotKey 'Do stuff here that you want to happen when your hotkey is pressed End If End If MyBase.WndProc(m) End Sub