KeyPress not fired in some cases when Form.KeyPreview is on

R

Rene

Hi,

I am running is some problems with the KeyPreview and KeyPress events.

The KeyPress event is only triggered when there this an focusable control on
the form. When all controls are disabled the Form.KeyPress event does not
trigger anymore.

A way to 'solve' this is to set the focus to the form, but during testing it
happens ofter the keypress event is not getting triggered on keys like
ENTER. Clicking a few times on the main form will get the even triggered
again.

Is there a good solution to solve this, or is there a way to convert the
keys in ProcessCmdKey() to keydata?

TIA,

Rene
 
C

Christiaan Nijdam

Hi Rene,

It seems like the keyPress event doesn't trigger sometimes for the Enter key
because KeyDown doesn't. I don't know why or where the event goes. Have you
considered using only the KeyUp event?

Christiaan.


....
this.KeyDown += new KeyEventHandler(MyKeyDownEventHandler);
this.KeyPress += new KeyPressEventHandler(MyKeyPressEventHandler);
this.KeyUp += new KeyEventHandler(MyKeyUpEventHandler);
this.Click+=new EventHandler(MyClickEventHandler);

}

public void MyKeyDownEventHandler(object sender,KeyEventArgs e)
{
if (e.KeyCode==Keys.Enter) System.Console.Write("ENTER");
System.Console.WriteLine("down");
e.Handled=true;
}

public void MyKeyUpEventHandler(object sender,KeyEventArgs e)
{
if (e.KeyCode==Keys.Enter) System.Console.Write("ENTER");
System.Console.WriteLine("up");
e.Handled=true;
}

public void MyKeyPressEventHandler(object sender,KeyPressEventArgs e)
{
if (e.KeyChar==13) System.Console.Write("ENTER");
System.Console.WriteLine("press");
e.Handled=true;
}

public void MyClickEventHandler(object sender,EventArgs e)
{
button1.Enabled=!button1.Enabled;
}

....
this.KeyPreview = true;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top