我想将鼠标光标位置更改为焦点控件。我通过键盘更改焦点(Enter键)。我怎样才能做到这一点?
干得好:
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,如此处所示..:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter) { goToActive(); return true;}
return base.ProcessCmdKey(ref msg, keyData);
}
更新:如果您不想按Enter键而是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
。
我已经对其进行了测试,但是可以注意到,我宁愿不要让我的光标跟踪我的焦点。.使其成为一个选项,而不是一个功能!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句