gpt4 book ai didi

c# - 将鼠标光标位置更改为焦点控制

转载 作者:行者123 更新时间:2023-11-30 20:43:18 25 4
gpt4 key购买 nike

我想将鼠标光标位置更改为焦点控制。我通过键盘(回车键)改变焦点。我怎样才能做到这一点?

最佳答案

给你:

void goToActive()
{
Control ctl = this.ActiveControl;
this.Cursor = new Cursor(Cursor.Current.Handle);
if (ctl != null) Cursor.Position = ctl.PointToScreen(new Point(3,3));
}

要从任何地方捕获您的导航键,请将 ProcessCmdKey 重写为 show here ..:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter) { goToActive(); return true;}
return base.ProcessCmdKey(ref msg, keyData);
}

更新:如果您不想跟随 Enter-Key 而是跟随您控件的 Enter 事件,请按以下步骤操作:

我们在 Form.Shown 事件中注册所有控件:

private void Form1_Shown(object sender, EventArgs e)
{
registerAllControls(this);
}

这会递归地注册所有控件。你可能想根据你的需要排除一些,也许检查名称、类型或 Tag..:

void registerAllControls(Control ctl)
{
ctl.Enter += ControlReceivedFocus;
foreach (Control ct in ctl.Controls)
{
registerAllControls(ct);
}
}

只有当我们不在此处时,我们才调用修改后的 goToActive 函数..:

void ControlReceivedFocus(object sender, EventArgs e)
{
if (!((sender as Control).ClientRectangle
.Contains(PointToClient(MousePosition))))
{
goToActive(sender);
}
}

我修改了函数以包含调用控件,使事情变得更容易一些..:

void goToActive(object sender)
{
Control ctl = sender as Control;
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = ctl.PointToScreen(new Point(3, 3));
if (sender is TextBox) Cursor = Cursors.IBeam;
else Cursor = Cursors.Default;
}

请注意,Cursor 倾向于选择错误的形状;我将其设置为 Default,或者将 TextBoxes 设置为 IBeam

我已经对其进行了测试,它有效,但是,如前所述,我不想让我的光标跟踪我的焦点。让它成为一个选项,而不是一个功能!

关于c# - 将鼠标光标位置更改为焦点控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30681656/

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