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);
}
Related
I created a control (called Table) made up by two pictureBoxes and two Labels.
I'm trying to drag and drop it from a panel to another, but it doesn't work.
This is my code:
void TableExampleMouseDown(object sender, MouseEventArgs e)
{
tableExample.DoDragDrop(tableExample, DragDropEffects.Copy);
}
void Panel2DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
void Panel2DragDrop(object sender, DragEventArgs e)
{
panel2.Controls.Add((Table) e.Data.GetData(e.Data.GetFormats()[0]));
}
Obviously I've set AllowDrop to true in panel2. Already when I click on Table object (which is in panel1), the mouse cursor doesn't change. It looks like the MouseDown event doesn't fire...
Thank you!
This is the part of the constructor code in which I subscribe Handlers:
this.tableExample.MouseDown += new System.Windows.Forms.MouseEventHandler(this.TableExampleMouseDown);
this.label2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Label2MouseDown);
this.panel1.DragDrop += new System.Windows.Forms.DragEventHandler(this.Panel1DragDrop);
this.panel1.DragEnter += new System.Windows.Forms.DragEventHandler(this.Panel1DragEnter);
You seem to have forgot to subscribe to the MouseDown event. Simply writing an event hanlder isn't enough.
Put this in the Form_Load event handler or in the form's constructor:
tableExample.MouseDown += new MouseEventHandler(TableExampleMouseDown);
For more information refer to the documentation: How to: Subscribe to and Unsubscribe from Events - Microsoft Docs.
EDIT:
It could also be that you press one of the child controls of your custom control. Child controls have their own MouseDown events.
To make the child controls also raise the parent control's MouseDown event put this in the constructor of your custom control:
MouseEventHandler mouseDownHandler = (object msender, MouseEventArgs me) => {
this.OnMouseDown(me);
};
foreach(Control c in this.Controls) {
c.MouseDown += mouseDownHandler;
}
EDIT 2:
Based on the new code you added to the question you seem to have forgotten to subscribe to the events for panel2:
this.panel2.DragDrop += new System.Windows.Forms.DragEventHandler(this.Panel2DragDrop);
this.panel2.DragEnter += new System.Windows.Forms.DragEventHandler(this.Panel2DragEnter);
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;
}
}
}
}
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();
}
MouseWheel event doesn't fire
when I' am using any control (ListBox, Panel, TextBox) with scrollbars.
To reproduce problem:
public class Form1 : Form
{
private readonly Button button1;
private readonly TextBox textBox1;
private void button1_MouseWheel(object sender, MouseEventArgs e)
{
ToString(); // doesn't fire when uncomment lines below
}
public Form1()
{
button1 = new Button();
textBox1 = new TextBox();
SuspendLayout();
button1.Location = new System.Drawing.Point(80, 105);
button1.Size = new System.Drawing.Size(75, 23);
button1.MouseWheel += button1_MouseWheel;
button1.Click += button1_Click;
textBox1.Location = new System.Drawing.Point(338, 105);
//textBox1.Multiline = true; // uncomment this
//textBox1.ScrollBars = ScrollBars.Vertical; // uncomment this
textBox1.Size = new System.Drawing.Size(100, 92);
ClientSize = new System.Drawing.Size(604, 257);
Controls.Add(textBox1);
Controls.Add(button1);
ResumeLayout(false);
PerformLayout();
}
// Clicking the button sets Focus, but even I do it explicit Focus() or Select()
// still doesn't work
private void button1_Click(object sender, System.EventArgs e)
{
button1.Focus();
button1.Select();
}
}
I was having the same problem, and what worked for me was to add a handler for the event MouseEnter in the control, that one is triggered with or without focus.
private void chart1_MouseEnter(object sender, EventArgs e)
{
chart1.Focus();
}
After that I could get the mouseWheel events with no problems.
You normally need to make sure the control you want to handle the MouseWheel event is active.
For example try calling button1.Select() in the Form Load (or Shown) event and then using the scroll wheel.
eg:
private void Form1_Load(object sender, EventArgs e)
{
button1.MouseWheel += new MouseEventHandler(button1_MouseWheel);
button1.Select();
}
I found solution, gility is default "Mouse Configuration". Lenovo USB Optical Wheel Mouse default configuration is:
Control Panel/Mouse/Wheel/Whell->Enable Universal Scrolling;
I changed to:
Control Panel/Mouse/Wheel/Whell->Use Microsoft Office 97 Scrolling Emulation Only
Now in .net code MouseWheel working with Focused Control.
But questions are:
how can I fix it in .net code?
how can I detect this situation in .net code?
Any ideas ?
I tried your example, and, whether the lines were commented or not, the MouseWheel event only fires if the button is focused. This behavior is by design. (the MouseWheel event, like keyboard events, goes to the focused control)
I wanted to know if it was possible to create a control from another control and which this new control could process certain events.
For example, lets say we have a Button that once it is clicked on will create a ComboBox. Could this new ComboBox be capable of processing a certain event such as a SelectionChanged event?
Sure thing. Simply provide an event handler and hook it up to the event:
public Window1()
{
InitializeComponent();
Button button = new Button();
button.Click += new RoutedEventHandler(button_Click);
}
void button_Click(object sender, RoutedEventArgs e)
{
ComboBox combo = new ComboBox();
combo.SelectionChanged += new SelectionChangedEventHandler(combo_SelectionChanged);
}
void combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Do your work here.
}