-
c# key events
I am still learning c# and now i face a problem.
How do make my application do things on keyboard commands?
here is the code i currently use and it does nothing?
Code:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control == true && e.KeyCode == Keys.I)
{
label1.Text = "Ctrl + I was pressed";
// Don't pass message to other controls
e.Handled = true;
}
}
-
Re: c# key events
Have you assigned the event handler to the right event? Is it entering the method at all? Place a breakpoint on the if() line and see if it hits it.
-
Re: c# key events
it dosent seem to hit...
no errors no nothing :S
-
Re: c# key events
How are you assigning the event handler?
-
Re: c# key events
?
can you put it a little clearly? i am not understanding
-
Re: c# key events
Just because you've called it Form1_KeyDown doesn't mean that it'll automatically be called. You need to actually assign it:
Code:
public Form1()
{
// InitializeComponent() etc.
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
}
private void Form1_KeyDown(...) etc.
-
Re: c# key events
oh i see it now.
That bit of code wasn't there before in my method.
When i add it it works fine. Do I have to add it manually every time for each control?
-
Re: c# key events
Per event per control, yes.
-
Re: c# key events
Not all events, lets say you add a button and double click on it. The event handler for the click event will be automatically created. But the rest will need to be added manually.
-
Re: c# key events
That's just the designer adding the same line of code, that you could add yourself, to the .designer.cs file.
-
Re: c# key events
or you could just right click to your form and then properties, click the events button or the lightning icon and there listed all the events. Just assign a name of the events then hit enter.