问题描述
使用c#winforms vs2008
using c# winforms vs2008
我在一个表单上有一个文本框,其中一个方法是从textBox1_Leave事件中调用的。该方法接受所讨论的文本框的内容,并根据内容填充其他文本框。
我的问题是用户已经把重点放在文本框上,然后点击按钮关闭窗体(调用this.close),然后窗体不会关闭,因为文本框离开事件被触发。
如果文本框没有关闭窗体关闭,则表单将关闭。
I've got a textbox on a form with a method being called from the textBox1_Leave event. The method takes the contents of the textbox in question and populates other textboxes based on the contents.My problem is that is the user has focus on the text box then clicks the button to close the form (calling this.close) then the form does not close because the textbox leave event gets fired.If the textbox does not have focus on form close then the form closes fine.
如果用户通过单击窗口中的小X关闭图标来关闭窗体顶部的角落一直关闭文本框离开事件被触发的所有时间。
If however a user closes the form by clicking the little X close icon in the top corner the it closes fine all the time with out the textbox leave event being fired.
如何复制X关闭功能,以便我可以随时关闭窗体没有文本框休假事件被触发?
How can I duplicate the X close functionality so that I can always close the form without the textbox leave event being fired?
推荐答案
最简单的解决方案是在做你的后处理 - 但是您不能在 Leave
处理程序中执行此操作,因为此时焦点仍将在文本框上。
The simplest solution is going to be to check which control is actually focused before doing your post-processing - but you can't do it in the Leave
handler, because the focus will still be on the text box at that point.
相反,您需要将逻辑移至 LostFocus
事件,而不在设计器中。您必须在运行时连线:
Instead, you need to move your logic to the LostFocus
event, which is not in the designer. You'll have to wire it up at runtime:
public class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.LostFocus += new EventHandler(textBox1_LostFocus);
}
private void textBox1_LostFocus(object sender, EventArgs e)
{
if (closeButton.Focused)
return;
// Update the other text boxes here
}
}
LostFocus
事件发生在新控件接收焦点后触发。
澄清 - 您可以通过将此逻辑放在 Leave
事件 - 中,如果焦点是由鼠标更改。如果使用键盘,则会产生错误的行为。 LostFocus
在 两种情况下都是可靠的 - 集中控制将始终成为新控件。这在MSDN上有记录:。
Clarification - you might find that it works by putting this logic in the Leave
event - if the focus is changed by the mouse. If the keyboard is used instead, you'll get the wrong behaviour. LostFocus
is reliable in both cases - the focused control will always be the "new" control. This is documented on MSDN: Order of Events in Windows Forms.
顺便提一句,你没有使用红色X问题的原因是X实际上不是可以接收焦点的控件,它是窗口的一部分。当用户单击该项时,不会导致文本框失去焦点,因此不会导致 Leave
事件触发。
Incidentally, the reason why you're not having this problem with the "red X" is that the X is not actually a control that can receive focus, it's part of the window. When the user clicks that, it's not causing the text box to lose focus, and therefore isn't causing the Leave
event to fire.
这篇关于如何停止文本框离开事件触发窗体关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!