C# 当表单被聚焦时发生的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1979213/
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
Event which occurs when form is focused
提问by Harikrishna
I have two forms first is frmBase and second is frmBalloon.I alter the focus of both forms that first frmBase is shown then frmBalloon is shown(frmBase is not visible)and then again frmBase is shown.Now I have need of event that occurs first frmBase loads and then again when it shows after frmBalloon becomes not visible.
我有两个表单,第一个是 frmBase,第二个是 frmBalloon。我改变了两个表单的焦点,首先显示 frmBase 然后显示 frmBalloon(frmBase 不可见)然后再次显示 frmBase。现在我需要首先发生的事件frmBase 加载,然后在 frmBalloon 变得不可见后显示时再次加载。
So I have need of event that occurs when form becomes focused.......
所以我需要在表单变得聚焦时发生的事件......
采纳答案by Jon Skeet
Is Form.Activated
what you're after?
是Form.Activated
你追求的吗?
My reason for suggesting this rather than GotFocus
is that the form itselfdoesn't get focus if the focus changes from one form to a control on a different form. Here's a sample app:
我之所以提出这个建议,而不是GotFocus
因为如果焦点从一个表单更改为另一个表单上的控件,则表单本身不会获得焦点。这是一个示例应用程序:
using System;
using System.Drawing;
using System.Windows.Forms;
class Test
{
static void Main()
{
TextBox tb = new TextBox();
Button button = new Button
{
Location = new Point(0, 30),
Text = "New form"
};
button.Click += (sender, args) =>
{
string name = tb.Text;
Form f = new Form();
f.Controls.Add(new Label { Text = name });
f.Activated += (s, a) => Console.WriteLine("Activated: " + name);
f.GotFocus += (s, a) => Console.WriteLine("GotFocus: " + name);
f.Show();
f.Controls.Add(new TextBox { Location = new Point(0, 30) });
};
Form master = new Form { Controls = { tb, button } };
Application.Run(master);
}
}
(Build this as a console app - that's where the output goes.)
(将此构建为控制台应用程序 - 这就是输出的位置。)
Put some name in the text box and click "new form" - then do it again. Now click between the text boxes on the new form - you'll see the Activated
event is getting fired, but not GotFocus
.
在文本框中输入一些名称,然后单击“新表单” - 然后再做一次。现在在新表单上的文本框之间单击 - 您将看到Activated
事件被触发,但不是GotFocus
。
回答by Oded
There is a Form.GotFocusevent.
有一个Form.GotFocus事件。
回答by casperOne
What about the GotFocus event?
怎么样的GotFocus事件?
Note that the GotFocus event on Control (from which Form is derived, so it applies here) is marked with the BrowsableAttribute, passing a value of false to the constructor, so it is notvisible in the properties window.
请注意,Control 上的 GotFocus 事件(从 Form 派生而来,因此它适用于此处)用BrowsableAttribute标记,将 false 值传递给构造函数,因此它在属性窗口中不可见。
You should add the event handler manually in code outsideof the designer-generated code.
您应该在设计器生成的代码之外的代码中手动添加事件处理程序。