Keypress event for dynamically created winform in C# - c#

I'm creating a windows form at run-time. Now i want the Key-press event to be triggered for the dynamically created form.
How do i create/bind the event to newly/dynamically created windows form in C#.
Thanks,

If we take a text box its like this.
private void Form1_Load(object sender, EventArgs e)
{
TextBox myTextBox = new TextBox();
myTextBox.KeyPress += new KeyPressEventHandler(myTextBox_KeyPress);
this.Controls.Add(myTextBox);
}
void myTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
//Do Key press event work here
}
UPDATE
Make sure that the focus should be on Form2.

Try This.
Form dynamicForm = new Form();
dynamicForm.KeyPress += new KeyEventHandler(onkeyPress);
void onkeyPress(object sender, KeyEventArgs e)
{
Console.WriteLine("test");
}

Make sure the forms KeyPreview Property is set to true, that way it will see the keystrokes.
From above link:
When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus. For example, if the KeyPreview property is set to true and the currently selected control is a TextBox, after the keystroke is handled by the event handlers of the form the TextBox control will receive the key that was pressed. To handle keyboard events only at the form level and not allow controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event handler to true.
So you will want to do something like this:
public partial class Form1 : Form
{
Form2 f2;
public Form1()
{
InitializeComponent();
KeyPreview = true;
KeyDown += Form1_KeyDown;
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.Control)
{
switch(e.KeyCode)
{
case Keys.C:
MessageBox.Show("Cntrl C");
break;
case Keys.V:
MessageBox.Show("Cntrl V");
break;
default:
break;
}
}
}
}

Related

MouseWheel Event On ComboBox Triggers KeyDown Event

Create a Windows Form (Net Framework or Net Core) and add a Toolstrip with ToolStripComboBox control. And then add these methods:
public Form1()
{
InitializeComponent();
KeyDown += Form1_KeyDown;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
//any code here;
}
If Form KeyPreview = false then Form1_KeyDown event is not triggered with MouseWheel event on ToolstripComboBox. Setting KeyPreview = true (is necessary) causes MouseWheel event is captured by Form1_KeyDown handler as Up or Down.
Is there a way to prevent Form_KeyDown handler Not To Handle MouseWheel event?
both using comments here as source and referencing vs code knowledge, one solution to this:
private void Form1_KeyDown(dynamic sender, KeyEventArgs e)
{
if (sender.GetType().Name != "Form1")
{
//code for action...
}
}

Resize on the key firing

I have a classic Form1 class that inherits the Form class.
The problem is I press the buttons and no events get fired.
Inside the Form1 there is a webBrowser which occupies the whole Form1.
Here is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
WindowState = FormWindowState.Maximized;
KeyPreview = true;
PreviewKeyDown += wb_PreviewKeyDown;
}
private void wb_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
Console.WriteLine("EDOOOOOOOOO");
if (e.Control && e.KeyCode == Keys.C)
{
// Do something funny!
}
}
}
The wb_PreviewKeyDown is not fired whatever button I push.
If you press a key on the form, the event will get fired.
However, if you have a TextBox or something on the form, and you press a key on that, the event will NOT fire, because now the TextBox has received the input.
This can easily be fixed by setting the property KeyPreview = true on the form.
You can set this in the designer, or in code (see the answer of #Isma)
EDIT:
Since you have a WebBrowser control on your form, you need to do it somewhat different, see this Handling key events on WebBrowser control
It involves using the PreviewKeyDown event of the WebBrowser

Invoking a Button Click Event of UserControl from its parent Form using Function Keys Like (F3,F6)

Code in User Control (Windows User Control).
I have a button and when click on the button some logic will fire.
below is button event.
private void btnCancel_Click(object sender, EventArgs e)
{
// Some Logic
}
I have Main form (Windows form)
I am adding the above user control in a Panel of my Main Winform.
From here I want to invoke the user control btnCancel_Click event using some function Keys Like (F3,F4).
This is a very new thing for me. Please help me in this regard.
Thanks .
Krishna
Set your parent form KeyPreview attribute to true and then in the KeyDown event of your parent form, look for if(e.KeyCode == Keys.F3), then write a public method for your usercontrol which fires the btnCancel_Click. You can access it from your parent form.
Parent Form:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F3)
{
MyUserControl.FireButtonEvent();
}
}
Usercontrol:
public void FireButtonEvent()
{
this.btnCancel_Click(null, EventArgs.Empty);
}
Create a KeyEvent method. for example:
private void KeyDown(Object sender, KeyEventArgs e)
{
string sKey = e.KeyValue.ToString();
if (sKey==112) {//SomeCode;} // F1
}
In the designer code link the method to a key press event on the main form:
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.KeyDown);
Look on the net for the key values of the button you want to activate it,
F1 to F24 are values 112 to 135.

GotFocus Event is not coming after created LostFocus Event in C#

I just want to clear the clipboard text if my form LostFocus. What I mean is that if a user copies something using his keyboard or mouse, have to clear it on LostFocus events, then I need to get my text back if my form receives focus again. How can I achieve this?
string sValue = "";
public Form1()
{
InitializeComponent();
this.LostFocus += new EventHandler(Form1_LostFocus);
this.GotFocus += new EventHandler(Form1_GotFocus);
}
void Form1_GotFocus(object sender, EventArgs e)
{
Clipboard.SetText(sValue);
textBox1.Text = Clipboard.GetText();
}
void Form1_LostFocus(object sender, EventArgs e)
{
sValue = textBox1.Text;
Clipboard.Clear();
}
This does not work; the LostFocus event is called, but GotFocus is not getting called. How can I solve this?
To give you a quick answer which works, instead of adding the event handlers to the form itself, add them to the TextBox control:
textBox1.LostFocus += new EventHandler(Form1_LostFocus);
textBox1.GotFocus += new EventHandler(Form1_GotFocus);
If the form contains any visible controls, it will never trigger the GotFocusor the LostFocus events.
But the recommended way to handle this behavior at the form level is to use:
this.Deactivate += new EventHandler(Form1_LostFocus);
this.Activated += new EventHandler(Form1_GotFocus);
or
textBox1.Leave += new EventHandler(Form1_LostFocus);
textBox1.Enter += new EventHandler(Form1_GotFocus);
Microsoft says:
For the Control.GotFocus Event
The GotFocus and LostFocus events are low-level focus events that are
tied to the WM_KILLFOCUS and WM_SETFOCUS Windows messages. Typically,
the GotFocus and LostFocus events are only used when updating UICues
or when writing custom controls. Instead the Enter and Leave events
should be used for all controls except the Form class, which uses the
Activated and Deactivate events.
For the Form.Activated Event
When the application is active and has multiple forms, the active form
is the form with the input focus. A form that is not visible cannot be
the active form. The simplest way to activate a visible form is to
click it or use an appropriate keyboard combination.
For the Control.Enter Event
The Enter and Leave events are suppressed by the Form class. The
equivalent events in the Form class are the Activated and Deactivate
events.
string sVal = "";
public Form1()
{
InitializeComponent();
this.Activated += new EventHandler(Form1_GotFocus);
this.Deactivate += new EventHandler(Form1_LostFocus);
}
void Form1_LostFocus(object sender, EventArgs e)
{
sVal = Clipboard.GetText();
Clipboard.Clear();
}
void Form1_GotFocus(object sender, EventArgs e)
{
Clipboard.SetText(sVal);
}

Why is there an infinite loop on my LostFocus Event

I'm a beginner with C# and I'm developing a basic application.
I want to check if the value of a textbox is a number with the following code :
private void check_value(object sender)
{
TextBox tb = (TextBox)sender ;
if (!Utility.isNumeric(tb.Text)){
MessageBox.Show(tb.Text.Length.ToString());
tb.Focus();
}
}
private void Amount_1_LostFocus(object sender, RoutedEventArgs e)
{
check_value(sender);
}
When I enter a letter in the textbox there is an infinite loop and it seems that the tb.Focus() actually cause the LostFocus event to be call recursively.
I don't understand why the call to the Focus method of an object triggers the LostFocus event of the same object.
Opening the modal MessageBox is responsible for loosing the focus. Try hook to Validating event.
As i said before in the link provided by Xaqron it's said that it's forbidden to use the Focus method in the LostFocus event.
And as I'm developing a WPF application there is no Validating event and CausesValidation property, so the others ways to validate the content is to use the TextChanged event or use binding validation.
Thank you for your answers.
Of course, in a perfectly valid program, you should not change Focus in the LostFocus event. This also applies to the Enter, GotFocus, Leave, Validating and Validated events, which Ms makes clear in the documentation https://learn.microsoft.com/pl-pl/dotnet/api/system.windows.forms.control.lostfocus.
However, in very unusual cases, you can use the timer to trigger changes to the Focus, bypassing this problem.
private TextBox tb = null;
private System.Windows.Forms.Timer MyTimer;
private void initialize()
{
MyTimer.Tick += new System.EventHandler(MyTimer_Tick);
MyTimer.Enable = false;
MyTimer.Interval = 100;
}
private void check_value(object sender)
{
tb = (TextBox)sender ;
if (!Utility.isNumeric(tb.Text)){
MessageBox.Show(tb.Text.Length.ToString());
MyTimer.Enable = true;
}
}
private void Amount_1_LostFocus(object sender, RoutedEventArgs e)
{
check_value(sender);
}
private void MyTimer_Tick(object sender, EventArgs e)
{
MyTimer.Enabled = false;
if (tb!=null) tb.Focus();
}

Categories

Resources