Possible Duplicate:
How to detect the currently pressed key?
(EDIT: For what it's worth, this is not a duplicate... not sure why it was voted as such)
I have a small timer application that we use in the office to track the hours spent on a project. There is a start and stop button, and a project and task fields. When we go on break and to lunch and other things, we stop the timer for that project, then restart it. This is a repetitive task that generally involves digging the window out from behind several other Windows, then the same after the break.
What I want to do is assign WindowKey+W to the work timer application and have it not only bring the timer application to the front and focus it, but also have it toggle the Start/Stop.
I have tried a number of searches, but I can't seem to narrow down the examples to what I want. I do know that you can open the properties of a Windows shortcut and assign a shortcut key to launch a program, and (I guess?) if you have that app already open and it is set to allow only one instance of the program that it will bring that program to the front??? maybe..
Anyway.. but that method will not accept the WindowsKey as a valid key combo. And I don't know if it can somehow pass that key combo in to the program.
I appreciate any help or direction here!!
EDIT - Answer Update
Thank you @huadianz for your answer! I converted your code to VB:
Public Const MOD_WIN As Integer = &H8
Public Const KEY_W As Integer = &H57
<DllImport("user32.dll")> _
Public Shared Function RegisterHotKey(hWnd As IntPtr, id As Integer, fsModifiers As Integer, vlc As Integer) As Boolean
End Function
<DllImport("user32.dll")> _
Public Shared Function UnregisterHotKey(hWnd As IntPtr, id As Integer) As Boolean
End Function
Public Sub RegisterKeys()
RegisterHotKey(Me.Handle, 1, MOD_WIN, KEY_W)
End Sub
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
MyBase.WndProc(m)
If (m.Msg = &H312) Then
Me.TopMost = True
Me.PlayPauseTimer()
Me.TopMost = False
End If
End Sub
On an interesting note, Me.BringToFront()
would not actually bring the application to the front in this scenario in Win7, nor did Me.Focus()
. However, Me.TopMost = True
worked, but it has the secondary effect of making the window always on top. Setting it to True
, toggling the timer, then setting it back to False
works great!