As in the event Form Closing I want to show a msgbox asking if I really want to put PC in to sleep mode and cancel the sleep order if the user answer "No".
I need to detect this even if the application is minimize or out of focus.
Thanks.
As in the event Form Closing I want to show a msgbox asking if I really want to put PC in to sleep mode and cancel the sleep order if the user answer "No".
I need to detect this even if the application is minimize or out of focus.
Thanks.
I don't have a sleep button on my keyboard, so I can't verify, but this might be worth a test...
In your active forms KeyDown event, put something like this:
Private Sub form_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)Handles Me.KeyDown
Select Case e.KeyCode
Case Keys.Sleep
'Do something when the sleep button is pressed
End Select
End Sub
If you want the keypress to not get sent to the active control in the form, add
e.Handled = True
I have learnt that in order for the main form to capture keypresses, the "KeyPreview" property of the form must be set to "True". If not the keypress will be sent to the control with focus.
I have also seen that there are differences in what keys can be detected in the KeyDown event and the KeyPress event. As an example, you can test for an arrow key in the KeyDown event, but not in the KeyPress event, as they are using a different event argument type, so it is worth checking both if you can't find the key you are looking for.
As to making it work when the program is not in focus, that appears to be more difficult. The following link shows how to register a HotKey which you can trap even when your program is not in focus: http://www.kirsbo.com/How_to_add_global_hotkeys_to_applications_in_VB.NET However, looking at the available key-codes to trap, I can not fins a Sleep or Power option. They can be found here: http://msdn.microsoft.com/en-us/library/ms927178.aspx
As I said, I can't verify that this works, but if you can, make a comment so other people will know.