gpt4 book ai didi

c# - 如何将焦点设置到用户控件

转载 作者:行者123 更新时间:2023-11-30 14:49:05 24 4
gpt4 key购买 nike

我有 50 个动态添加到 flowlayoutPanel 的用户控件。我需要将焦点设置到用户控件,但它不起作用。我一直在搜索,但找不到任何我理解的例子。

我找到的唯一例子是这个 Setting Focus to a .NET UserControl...?

我尝试使用 userCtrl.Focus();但它没有用。正如我一直在阅读的那样,用户控件不喜欢拥有焦点。

最佳答案

Addition: Now that I understand more of the Control class, I understand that if you derive from Control you should not subscribe to its events, but use the On.. functions, like OnEnter. I've changed my answer accordingly

要激活任何 Control,包括 UserControl,请使用 Control.Select()

如果您对 TextBox 执行此操作,您会看到 Select 确保它获得输入焦点。

我猜您想对选定的 UserControl(具有焦点的 Control)执行某些操作,例如,您想要更改其外观,或选择任何它上面的控件。为此,您的 UserControl 类必须订阅事件 Control.Enter 和 Control.Leave

我创建了一个带有 CheckBoxUserControl,只要选择 UserControl(具有输入焦点),它就会自动检查:

补充:如果您从控件派生,请不要订阅事件 EnterLeave。而是覆盖引发这些事件的函数: OnEnter/OnLeave .

public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}

protected override void OnEnter(EventArgs e)
{
this.checkBox1.Checked = true;
base.OnEnter(e); // this will raise the Enter event
}

protected override void OnLeave(EventArgs e)
{
this.checkBox1.Checked = false;
base.OnLeave(e); // this will raise the Leave event
}
}

我有一个带有按钮的表单,以及一个在单击按钮时调用的事件处理程序:

private void OnButton1Clicked(object sender, EventArgs e)
{
this.userControl1.Select();
}

现在,每当单击按钮时,我都会看到用户控件获得焦点,因为复选框已选中,而每当我单击其他地方时,复选框都未选中。

关于c# - 如何将焦点设置到用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39471972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com