very simple & strange error

  • Thread starter Thread starter Dave
  • Start date Start date
D

Dave

I build a very simple program that I put at the end of this post. This
program is just supposed to put a button on the screen and exit the program
when I press the escape button. But pressing the escape button doesn't do
anything if I put the code for the button into the program! infact, pressing
escape only works if you take away the little piece of code:
"this.Controls.Add(this.button1);"!! I was totally confused at why this
happened and would really like to fix it. any ideas? Ps: the code works if
instead of a button, I insert a label. it also doesn't work if I insert a
textbox.
thanks
dave


using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using Microsoft.DirectX;

using Microsoft.DirectX.Direct3D;

using System.Threading;



namespace re

{

public class Form1 : Form

{

private System.Windows.Forms.Button button1;



public Form1()

{

this.button1 = new System.Windows.Forms.Button();


this.SuspendLayout();

this.button1.Location = new System.Drawing.Point(670, 220);

this.button1.Name = "button1";

this.button1.TabIndex = 0;

this.button1.Text = "button1";

this.button1.Click += new System.EventHandler(this.button1_Click);

this.KeyUp += new KeyEventHandler(OnKeyPress);

this.Controls.Add(this.button1);


}

public void OnKeyPress(object sender, KeyEventArgs e)

{

if(e.KeyCode == Keys.Escape)

Application.Exit();

}

static void Main()

{

Application.Run(new Form1());

}

private void button1_Click(object sender, System.EventArgs e)

{


}

}

}
 
I couldn't get KeyPress to work with non-characters either.. Look into
ProcessDialogKey. Here's a decent article to get you started:
http://www.ondotnet.com/pub/a/dotnet/2002/04/29/keys.html?page=1 . Page 2
really has what you are looking for but the whole article is worth the read
to get the basics down.

Only problem for me was that it didn't work until I .Show() another form and
close it.. Then the origional form would capture the keys.. Weird. I'm
still trying to figure that one out, so please share the wealth if you
stumble across something.

good luck.
 
The answer seems to be that KeyPress is only supposed to work for regular
characters. that's what that tutorial you gave me was saying. The only
problem with using ProcessDialogKey exclussively is that it doesn't know the
difference between caps and lowercase characters. So, if you need caps and
lowercase, then use keypress. if not, use processdialogkey. but if you need
both non-character keys and caps/lowercase regular keys, just use both
together. That's my solution. does that solve your problem?
dave
 
Back
Top