C# Window_KeyUp() not working
Asked Answered
T

1

8

Hey I have this piece of code:

private void Window_KeyUp(object sender, KeyEventArgs e)
{
    if (playing == false)
    {
        return;
    }
    if (e.KeyCode == Keys.D1)
    {
        pictureBox6.Image = Form.Properties.Resources.black_square_button;
        player.Stop();
        player.Close();
        playing = false;
    }
}

I'ts not working but the Window_KeyDown() works.

What is wrong with my code?

Thanks.

Tiloine answered 2/6, 2013 at 22:22 Comment(6)
What part of it is not working? Is the event being fired? Are you sure the handler is wired up correctly to the form and/or the controller?Festoonery
The events are not fired after you release the key.Tiloine
Do you have the event setup for a specific controller or the form? I believe the keyUp method gets called if the target controller is in focus.Festoonery
Do you have this for a Form KeyUp event handler?Sexdecillion
@Sexdecillion Iam afraid i don't.Tiloine
@RezaShirazian yes, the event is setup specificly for the key D.1Tiloine
S
32

The KeyUp event (also KeyDown and KeyPress) are triggered at the form level only if the form has

KeyPreview = true; 

MSDN here

true if the form will receive all key events; false if the currently selected control on the form receives key events. The default is false.

Sexdecillion answered 2/6, 2013 at 22:30 Comment(7)
Well i already defined KeyPreview = true; as KeyDown works fine.Tiloine
Well that's interesting, what do you do in the KeyDown event? e.Handled=true;Sexdecillion
stop the sound triggered by KeyDown event and also change the image of a button, pretty simple but won't work.Tiloine
Whats with the "e.Handled=true;"?Tiloine
If you don't want a key to be further processed you could change the KeyEventArgs argument e passed to the event handler and set e.Handled = true;Sexdecillion
Could you confirm me that you have hooked the KeyUp event in the designer of your form?Sexdecillion
Oh, how careless I was, that was the problem, now it works. ThanksTiloine

© 2022 - 2024 — McMap. All rights reserved.