如何使控件失去焦点单击它之外的任何地方? [英] How can I make a Control lose focus clicking anywhere outside of it?

查看:47
本文介绍了如何使控件失去焦点单击它之外的任何地方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 UserControl(位于图像的中间顶部)在我点击它之外的任何地方时失去焦点.

I want my UserControl (at the middle-top in the image) to lose focus when I click outside of it, anywhere.

我已经试过了:

private void Form1_Click(object sender, EventArgs e)
{
    ActiveControl = null;
}

它仅在我单击 Form 本身、TrackBar 和 MediaPlayer 时才有效.当我点击其他控件时它不起作用,即使是 FlowLayoutPanel.
我该怎么办?

It only works when I click the Form itself, the TrackBar and the MediaPlayer. It doesn't work when I click other controls, even the FlowLayoutPanel.
What can I do about it?

推荐答案

Eric,

要从自定义控件中的项目中移除焦点,您需要一些其他可聚焦控件来传递焦点.我会做这样的事情:

To remove the focus from an item in your custom control, you will need some other focusable control to pass the focus to. I would do something like this:

private void StealFocus() => lbl_SomeLabel.Focus();

然后将 StealFocus() 放到表单的点击事件处理程序中:

And then drop StealFocus() in your form's click event handler:

private void Form1_Click(object sender, EventArgs e) => StealFocus();

以及用户可能点击但不执行命令的任何其他控件.

and any other control the user might click that doesn't execute a command.

请注意,您不能将焦点设置在表单上.像 Form 和 Panel 这样的容器控件会将 Focus 传递给它们的第一个子控件.这可能是您要从中移除焦点的自定义控件.

Note that you cannot set focus to the Form. Container controls like Form and Panel will pass the Focus on to their first child control. Which could be the custom control you wanted to remove focus from.

这篇关于如何使控件失去焦点单击它之外的任何地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆