[英]Change mouse cursor position to focused control
I want Change mouse cursor position to focused control. 我想将鼠标光标位置更改为焦点控件。 I change focuses by keyboard(Enter key).
我通过键盘改变焦点(输入键)。 How can I do this?
我怎样才能做到这一点?
Here you go: 干得好:
void goToActive()
{
Control ctl = this.ActiveControl;
this.Cursor = new Cursor(Cursor.Current.Handle);
if (ctl != null) Cursor.Position = ctl.PointToScreen(new Point(3,3));
}
To catch your navigation key from everywhere override ProcessCmdKey as show here ..: 要从任何地方捕获导航键,请覆盖ProcessCmdKey,如此处所示 ..:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter) { goToActive(); return true;}
return base.ProcessCmdKey(ref msg, keyData);
}
Update : If you'd rather not follow the Enter-Key but the Enter
events of your controls, here is how to do that: 更新 :如果您不想遵循Enter键,而是遵循控件的
Enter
事件,请按以下步骤操作:
We register all controls in the Form.Shown
event: 我们在
Form.Shown
事件中注册所有控件:
private void Form1_Shown(object sender, EventArgs e)
{
registerAllControls(this);
}
This regisers all controls recursively. 这将递归地监管所有控件。 You may want to exlude some based on your needs, maybe checking the name, type or
Tag
..: 您可能需要根据需要排除某些内容,例如检查名称,类型或
Tag
..:
void registerAllControls(Control ctl)
{
ctl.Enter += ControlReceivedFocus;
foreach (Control ct in ctl.Controls)
{
registerAllControls(ct);
}
}
We call the modified goToActive
function only when we are not here already..: 仅当我们还不在这里时,才调用修改后的
goToActive
函数。
void ControlReceivedFocus(object sender, EventArgs e)
{
if (!((sender as Control).ClientRectangle
.Contains(PointToClient(MousePosition))))
{
goToActive(sender);
}
}
I have modified the function to include the calling control, to make things a little easier..: 我修改了该函数以包括调用控件,使事情变得更简单。
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;
}
Note that the Cursor
has a tendency to pick up wrong shapes; 请注意,
Cursor
倾向于拾取错误的形状。 I set it to Default
or, for TextBoxes
to IBeam
. 我将其设置为
Default
或者将TextBoxes
为IBeam
。
I have tested it, it works, but, as noted, I'd rather not have my cursor track my focus.. Make it an option, not a feature! 我已经对其进行了测试,但是可以正常运行,但是,如前所述,我不想让我的光标跟踪我的焦点。.使其成为一个选项,而不是一个功能!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.