C# Keyboard button used to trigger a method - c#

I'm writing a Hangman program in C# and when I press a keyboard button I want the button on the form to be clicked. Where should I write this? In form1.load()?

No, you should select the Form on which you want the event to be triggered, then go to the properties pane, select the event tab and go down to KeyPress event, double click it and add some code.
Normaly something like this would do what you want, just google the KeyChar value to determine the keyPress you want to control, you can add more if statements:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
Button1.PerformClick();
}
//Other if statements if you want to keep an eye out for other keyPresses
}
[edit] I just remembered you might be also considering the shortcuts, in wich case the Button1.Text property should be marked &Button1, this way the "B" would be underlined and accept the alt+B shortcut to execute the button click event.
The & symbol is set before the letter you want for the shortcut, make sure you dont use the same letter for various buttons.

You wouldn't write the code in Form.Load() if you want it to happen in response to a keyboard event. That event occurs (and the code inside of it is executed) when your form first loads (appears on screen).
How about handling the KeyPress event and writing the code in that method, instead? Your form has one of those events, too.
Sample code:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
Button1.PerformClick();
}
The PerformClick method will generate a Click event for a Button control. You can handle that Click event in a similar way:
private void Button1_Click(object sender, EventArgs e)
{
// do something in response to the button being clicked
// ...
MessageBox.Show("Button clicked!");
}
If this event-handling stuff is confusing to you, make sure that you pick up a good book on programming in C# and/or the .NET Framework so that you learn it well. It's very important and not something to skip!

You have to enable KeyPreview property on the form, then you have to implements the KeyPress event directly on the form :
Form1.KeyPress +=new KeyPressEventHandler(Form1_KeyPress);
private void Form1_KeyPress(object sender, KeyPressEventArgs e) {
if(e.KeyCode == someKey) {
button1.performclick();
}
}

private void Form_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Left)
{
// Do your hang job
Button_Click(sender, EventArgs.Empty);
}
}

You need to subscribe to the events of interest and process them after. But before you need to read and study how to do that. It's a not a difficult issue in C#.
http://msdn.microsoft.com/en-us/library/ms171534.aspx
One time subscribed to the events create a function that you can call from button click and from keydown.

Related

SendKeys.send is sending more than one character

sorry for my bad english.
I am writing a keyboard application for the touchscreen. but,
for example, when I press the A key, sometimes it's writes 5 times A key . I am using basically button click event.
private void button42_Click(object sender, EventArgs e)
{
SendKeys.Send("A");
Thread.Sleep(100);
}
there is no problem with the mouse_click event. just touch
how can i do it?
1.Try handling it in a mouse_up or touch_up event instead of using a delay here. Actual implementation and events will depend on you framework.
mouse_up /touch_up will make sure that you even only fires when touch is released.
To add repetition on touch and hold, you may have to add additional logic however.
Try declaring a field to toggle the value of event fired.
private bool handling=false;
private void button42_Click(object sender, EventArgs e)
{
if(!handling)
{
handling=true;
SendKeys.Send("A");
Task.Delay(100).Wait();
handling=false;
}
}

C# WinForms - Detect User Click Into Text Box

I have been developing a windows form application and ran into a problem.
After trying various things (Listed below) I have come to seek your knowledge to help point me in the right direction.
I have replicated a much simpler version of my program:
As you can see, I have two textboxes. I want to be able to click on the textbox on the bottom (textbox1) and call some form of an event, in this case, for simplicity, pop up a message box.
I have been through the events listed here:
https://msdn.microsoft.com/en-us/library/system.windows.forms.textbox_events(v=vs.110).aspx
And implemented them into my code as I expected one of them to work. However, this is not the case.
private void textBox1_TextChanged(object sender, EventArgs e)
{
MessageBox.Show("TextBox Entered");
}
//Above - Will pop message box when text entered.
private void textBox1_GotFocus(object sender, EventArgs e)
{
MessageBox.Show("TextBox Entered");
}
private void textBox1_Enter(object sender, EventArgs e)
{
MessageBox.Show("TextBox Entered");
}
private void textBox1_Click(object sender, EventArgs e)
{
MessageBox.Show("TextBox Entered");
}
Does anybody know what I am missing? I presume what I am trying to achieve is actually possible?
Kind Regards,
B.
Ensure the event is subscribed to the methods you have written. You can do this in the design view using the Events tab of the property window (looks like a lightning bolt). As mentioned by others, a double click in the events window will generate the event's method for you, and subscribe to it automatically.
Another way is to subscribe directly using code; you could write this in the form constructor for example:
textBox1.TextChanged += textBox1_TextChanged;

Method for Focus Change

Is there a method which initiates on focus change and can be overridden?
My goal is for the program to fetch closest data automatically from database to input fields whenever user changes his focus/presses enter or tab when on corresponding field. I'm still looking for a way to do this when user selects an item by mouse.
I'm aware that this could be implemented on mouse click but I refuse to believe that there is not a general method for focus change.
What about something like this:
foreach(Control ctrl in this.Controls)
{
ctrl.Enter += new EventHandler(Focus_Changed); // Your method to fire
}
Iterate through all controls and add a enter-event. Bind this handler to your method.
Edit:
Just in case you are wondering why "Enter" and not "LostFocus" or something like that: From my knowledge not every control got focus-events. As I've seen so far "Enter" is presented for all. Maybe there are exceptions. Should be checked out...
You could use Control.Enter event and Control.Leave event for that purpose.
See on MSDN Control.Enter and
Control.Leave.
textBox1.Enter += textBox1_Enter;
textBox1.Leave += textBox1_Leave;
private void textBox1_Enter(object sender, System.EventArgs e)
{
// the control got focus
}
private void textBox1_Leave(object sender, System.EventArgs e)
{
// the control lost focus
}

Navigation in Windows Forms using enter key

I have textboxes in my Windows Forms application, and I want that when the user presses the ENTER key then the cursor goes to the next textbox.
How do I do this?
Is this a good habit or shall I avoid it? Actually the users are very much prone and have adapted and have become habitual of pressing ENTER key for navigation between textboxes and buttons. So, for them I need to do this.
Please help me with the complete code using two text-boxes as an example.
I would say the nicest way is to create a user control that inherits from TextBox and then override the OnKeyPress method to capture enter and send a tab. Focus will then be given to the next TabIndex on the form, just as though a tab had actually been entered.
The code below does exactly that:
public partial class CustomTextbox : TextBox
{
public CustomTextbox()
{
InitializeComponent();
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
e.Handled = true;
SendKeys.Send("{TAB}");
}
}
}
You could also put similar code in the KeyPress event handlers for your controls but this saves a lot of duplicate code and unnececessary event handler.
As for whether this is good practice - I would say in general, no, changing the default behaviour of forms is never a good idea, but of course, if this is what your users want and expect, then it is their decision.
This is a bad idea. The standard UI is for TAB to move between input fields. You make your app less useable when you elect not to follow well known standards. These standards are what makes UI intuitive.
Yes, it depends on you
For a sample, you can place 4 textbox on the form and use the following code
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox2.Focus();
}
}
private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox3.Focus();
}
}
private void textBox3_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox4.Focus();
}
}
It might help you.
Happy coding...
For example you could trap OnKeyUp event, check if it is RETURN and process source control to use Focus() to next control...
Yes you can fire the KeyDown or KeyUp event on a TextBox. To check whether it was the enter key, you can do the following:
//e is the KeyEventArgs from the event.
e.KeyCode == Keys.Enter
Then, if he has pressed the enter key, you can do:
System.Windows.Forms.Control.SelectNextControl();
To set the order of your controls, in Visual Studio look for this little icon:
http://i.stack.imgur.com/nZWLO.png
Click it, and you'll go into tab ordering mode, as I like to call it. Just click the controls in the order you wish them to be and after you're done, click the little icon again. Presto!
Now whether that is a good idea of not, completely depends on how used to it your end users are. If they have always used it like this, and you give them something that doesn't fit into their mind model, they are going to say your software is broken.
Always always always try to emulate what processes the user already has in place in their head.
Read this if you have the time, it's a really light and very good read:
http://www.joelonsoftware.com/uibook/fog0000000249.html
I think the best way would be to:
1) assign each textbox's TabIndex attribute incrementally (first is x, next is x+1 etc).
2) capture on the OnKeyUp event on the whole form, check the argument to see if the key was RETURN
3) focus the next textbox using its TabIndex. Or simulate the TAB key.
This code should work:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
GetNextControl((TextBox)sender, true);
}
}
This way you end up writing only one function, and you can have as many textboxes as you want.

Processing unprocessed enter key c#

I have to process enter (among other keys) on win form without it producing error sound, but only if the currently active control didn't process it already.
So, when enter is pressed while in a TextBox or DateTimePicker, i want to process it with a form (without error sound), but if it is pressed, for example, in DataGridView i want it to be handled the way DataGridView does by default.
OnKeyUp solves my problem with handling only unhandled keystrokes (e.Handled) and ProcessCmdKey (this) solves sound problem, but neither solves both.
Any suggestions?
Kudos for the very interesting question. Unfortunately, I can't seem to find a global event handler for all key presses other than overriding ProcessCmdKey on the main form per this article. Only issue with this method is that the arguments passed into the event handler delegate don't define what control is creating the event :(
So, my only thought is that you need to assign your event handler to every single control in the application. I've written some code that should help show you how to do this. I'm not sure what the adverse effects may be of assigning a KeyPress event handler to every control on your page though, but it's the only feasible solution I see.
Code:
private void Form1_Load(object sender, EventArgs e)
{
AssignHandler(this);
}
protected void HandleKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter && (sender != this.textBoxToIgnore || sender ! this.gridViewToIgnore))
{
PlaySound(); // your error sound function
e.Handled = true;
}
}
public void AssignHandler(Control c)
{
c.KeyPress += new KeyPressEventHandler(HandleKeyPress);
foreach (Control child in c.Controls)
{
AssignHandler(child);
}
}

Categories