3

如何将 .net 应用程序的焦点锁定到特定控件?例如,如果我有一个包含 5 个文本框的表单,并且我希望它们按特定顺序填写,我如何阻止框 1 中的人点击/单击框 2,或者点击确定或取消或其他任何东西? 有没有简单的方法,或者我必须在适当的时候手动禁用/启用彼此的控件?

显而易见的解决方案(当焦点丢失时重置焦点)的问题在于 MSDN 说您可以通过这种方式锁定您的机器:

(来源:http: //msdn.microsoft.com/en-us/library/system.windows.forms.control.leave.aspx

警告:

不要尝试从 Enter、GotFocus、Leave、LostFocus、Validating 或 Validated 事件处理程序中设置焦点。这样做可能会导致您的应用程序或操作系统停止响应。有关详细信息,请参阅“键盘输入参考”部分中的 WM_KILLFOCUS 主题,以及位于http://msdn.microsoft.com/library的 MSDN 库中“关于消息和消息队列”主题的“消息死锁”部分.

4

3 回答 3

4

处理 textBox1 的 Leave 事件。在事件处理程序中,如果不满足您的条件,例如,如果用户没有输入某些输入,则将焦点重置回控件。

private void textBox1_Leave(object sender, EventArgs e)
{
    if string.isNullOrEmpty(textBox1.Text)
    {
        textBox1.focus();
    }
}

为您的每个控件执行此操作,或者执行更通用的操作,例如:

private void textBox_Leave(object sender, EventArgs e)
{
    TextBox textBox = sender as TextBox;
    if (string.isNullOrEmpty(textBox.Text)
    {
        textBox.focus();
    }
}
于 2008-11-11T20:34:35.113 回答
3

基本上,您的设计必须严格。

  • 检查文本框何时失去焦点,如果它没有有效的数据输入,则重新获得焦点。
  • 当表单试图关闭时捕获——检查文本框是否有正确的数据,如果它没有取消关闭。
  • 捕获鼠标事件并检查数据,无论用户尝试什么,都将焦点发送到您想要的位置。

尽管如此,这是一个坏主意,会导致疯狂的用户。我的建议是为您的数据输入提出另一种范式,它可以处理以稳健的形式接收数据,而不是在您的设计中作恶并强制执行某些行为。

于 2008-11-11T20:36:02.723 回答
2

I think TextBox.Validating event is more appropriate, and it's meant for this specifically. Also it's much easier as you don't have to set the focus, all you need to do is set e.Cancel = true; to return focus to the current control

    void textBox1_Validating(object sender, CancelEventArgs e)
    {
        if (true) //Condition not met
        {
            e.Cancel = true;//Return focus to the current control
        }
    }

Make sure the CauseValidation under the property of the textbox is true, which is by default set to true anyway.

于 2008-11-12T08:05:13.550 回答