keypress problem

  • Thread starter Thread starter Jeroen Ceuppens
  • Start date Start date
J

Jeroen Ceuppens

Hi, I want to create the following:
when i press escape , the program must set draw to false

so it put these code in my form:

this.KeyPress += new
System.Windows.Forms.KeyPressEventHandler(this.Form1_KeyPress);

private void Form1_KeyPress(object sender, KeyPressEventArgs e)

{

if (e.KeyChar.Equals(Keys.Escape))

draw=false;

}





But the program doensn't work, when i press escape it does nothing, even
when i set a break on if (e.KeyChar.Equals(Keys.Escape)), it doens't get
there



Greetz

JC
 
Is your program perhaps elsewhere stuck in some loop that
is not yieldeing to allow the processing of events?

The cheap way to yield in that case would be to throw a
DoEvents in although probably doing a
PeekMessage/DispatchMessage would be more efficient.
 
What's setting of your draw variable to false supposed to
do? If it's a flag that's used in your OnPaint event to
indicate to draw or not something, you'd need to add a
this.Invalidate() call in the KeyPress event.

-Alex
 
Hi Jeroen,

I believe your form is not getting the KeyPress event because another
control has the focus at that time (keyboard events don't bubble up in
the CF).

You could try to set the focus back to the form every time it loses
it, like :

this.LostFocus +=new EventHandler(nameOfYourForm_LostFocus);

private void nameOfYourForm_LostFocus(object sender, EventArgs e)
{ this.Focus(); }

But this can lead to problems (like other controls never getting the
focus :), so I would rather create a menu item with the Esc shortcut
assigned to it, calling a method with only :

private void myMenuItem()
{ draw = !draw }

This will act as an on/off switch.

You might even be able to set that menu item hidden, but I'm not sure
about it. Worth a try.

HTH,

Michel
 
The Escape key does not work for me in the Emulator. Not
sure if this is a universal problem.

Are you testing this through the emulator? If so, try
uploading to your handheld and testing on it instead.

Cheers, Ian
 
fd123456 said:
Hi Jeroen,

I believe your form is not getting the KeyPress event because another
control has the focus at that time (keyboard events don't bubble up in
the CF).

You could try to set the focus back to the form every time it loses
it, like :

this.LostFocus +=new EventHandler(nameOfYourForm_LostFocus);

private void nameOfYourForm_LostFocus(object sender, EventArgs e)
{ this.Focus(); }

But this can lead to problems (like other controls never getting the
focus :), so I would rather create a menu item with the Esc shortcut
assigned to it, calling a method with only :

private void myMenuItem()
{ draw = !draw }

This will act as an on/off switch.

You might even be able to set that menu item hidden, but I'm not sure
about it. Worth a try.

I think the better way is to use P/Invoke RegisterHotKey to handle all
keydown messages for the form.
 
Back
Top