1

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.

E_Blue
  • 1,021
  • 1
  • 20
  • 45
  • FYI: http://stackoverflow.com/q/14593834/1768303 – noseratio May 03 '14 at 03:06
  • 1
    Thanks, reading that link I found SystemEvents.PowerModeChanged Event, I will test that. – E_Blue May 03 '14 at 03:19
  • Please let us know if you find a solution. You can accept your own answer. – Zairja May 10 '14 at 08:30
  • 1
    @Zairja - Hi, didn't test it yet; I just trying to make a silly application that warning me when some download is in progress in Firefox because I have the habit of press the sleep button when I'm getting away from the PC some times, but I found a plug-in. Anyway, I think I going to create that application because some times when I'm playing on some game I hit the sleep button by mistake. – E_Blue May 12 '14 at 15:26

1 Answers1

0

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.

Pingu
  • 1
  • 2