windows Control.Enter 和 Control.GotFocus 事件之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2702055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:20:23  来源:igfitidea点击:

What is the difference between the Control.Enter and Control.GotFocus events?

windowswinformsuser-interfaceevents

提问by jameswelle

This may be a basic question, but I have to admit I've never truly understood what the difference between the Control.Enter and Control.GotFocus events is.

这可能是一个基本问题,但我必须承认我从未真正理解 Control.Enter 和 Control.GotFocus 事件之间的区别。

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.enter.aspxhttp://msdn.microsoft.com/en-us/library/system.windows.forms.control.gotfocus.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.enter.aspx http://msdn.microsoft.com/en-us/library/system.windows.forms.control .gotfocus.aspx

Is it a differentiation between capturing keyboard or mouse input or something else?

捕获键盘或鼠标输入或其他东西之间是否有区别?

回答by Hans Passant

The GotFocus/LostFocus events are generated by Windows messages, WM_SETFOCUS and WM_KILLFOCUS respectively. They are a bit troublesome, especially WM_KILLFOCUS which is prone to deadlock. The logic inside Windows Forms that handles the validation logic (Validating event for example) can override focus changes. In other words, the focus actually changed but then the validation code moved it back. The logical state of your UI is that it never moved and you shouldn't be aware that it did.

GotFocus/LostFocus 事件分别由 Windows 消息 WM_SETFOCUS 和 WM_KILLFOCUS 生成。它们有点麻烦,尤其是容易死锁的 WM_KILLFOCUS。Windows 窗体中处理验证逻辑(例如验证事件)的逻辑可以覆盖焦点更改。换句话说,焦点实际上发生了变化,但随后验证代码将其移回。您的 UI 的逻辑状态是它从未移动,您不应该意识到它移动了。

The Enter/Leave events avoid the kind of trouble these low-level focus change notification events can cause, they are generated when Winforms has established the true focus. You almost always want to use these.

Enter/Leave 事件避免了这些低级焦点更改通知事件可能导致的麻烦,它们是在 Winforms 建立真正的焦点时生成的。您几乎总是想使用这些。

回答by Hans Passant

Control.Enter event happens when a control gets focus for the first time. While Control.GotFocus happens EVERY time a control gets focus. For example, you have 'textBox1' that already has focus and you call textBox1.Focus(), the GotFocus event will always fire in this instance, unlike for the Enter event that will only fire if a control doesn't already have the focus and receives it for the first time.

Control.Enter 事件在控件第一次获得焦点时发生。而 Control.GotFocus 每次控件获得焦点时都会发生。例如,您有一个已经获得焦点的“textBox1”并且您调用 textBox1.Focus(),GotFocus 事件将在此实例中始终触发,这与 Enter 事件不同,后者仅在控件尚未获得焦点时触发并第一次收到它。