20
private void screensaverWindow_Load(object sender, System.EventArgs e)
{            
    this.BringToFront();            
    this.Focus();
    this.KeyPreview = true;
    this.KeyDown += new KeyEventHandler(onkeyDown);            
}        

onKeyDown() is never called. Any idea why?

EDIT: This works in release mode!? I guess it must be visual studio debugger interfering somewhere

1
  • 2
    Does focus go to another control, like a textbox, after it has finished loading?
    – Iain Ward
    Jul 26, 2010 at 12:56

3 Answers 3

77

This is caused by the interception of events by child controls on form. If this is not desirable, you need set KeyPreview property of parent form to True

1
  • this should be the accepted answer
    – LairdPleng
    Sep 26, 2021 at 5:33
16

Seems to work for me:

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    this.BringToFront();
    this.Focus();
    this.KeyPreview = true;
    this.KeyDown += new KeyEventHandler(Form1_KeyDown);
}

void Form1_KeyDown(object sender, KeyEventArgs e)
{
    Console.WriteLine("test");
}

Are there any child controls on your form ?

2
  • One label, but that isn't firing any key events either.
    – user181351
    Jul 26, 2010 at 13:01
  • I'm not having problems with the example either. Seems to work as expected. Lose the other controls on the page and then attempt to reproduce. My guess is akin to the others here, you've likely got some other control that has focus.
    – Bob G
    Jul 26, 2010 at 13:52
1

How about menus, do you have menus with shortcut keys defined? I had an issue where a context menu that was hidden was actually swallowing cetain keys and not passing them on to any of the form key events

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.