繁体   English   中英

防止按钮聚焦

[英]Prevent button getting focus

我有几种形式的解决方案,每种形式都有TextBox的控件/控件和一个用于显示SIP的按钮(底部栏处于隐藏状态)。

当用户单击我的SIP按钮时,将启用SIP,但现在焦点是按钮。 我希望用户单击按钮-显示SIP,但将焦点保留在用户单击按钮之前具有焦点的控件上。 有谁知道如何做到这一点? 谢谢。

可以使用Control类并覆盖OnPaint方法来创建自定义按钮,而不是使用标准按钮。 默认情况下,在处理Click事件(在VS2008 netcf 2.0上测试)时,以这种方式创建的控件将不会声明焦点。

public partial class MyCustomButton : Control
{
    public MyCustomButton()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        pe.Graphics.DrawString("Show SIP", Font, new SolidBrush(ForeColor), 0, 0);
        // Calling the base class OnPaint
        base.OnPaint(pe);
    }
}

nathan的解决方案也将适用于Compact Framework或本机Windows Mobile应用程序。 在文本框中,GotFocus设置了一个全局变量,并在按钮单击事件中使用它来将焦点设置回上一个活动文本框:

    //global var
    TextBox currentTB = null;
    private void button1_Click(object sender, EventArgs e)
    {
        inputPanel1.Enabled = !inputPanel1.Enabled;
        if(currentTB!=null)
            currentTB.Focus();
    }

    private void textBox1_GotFocus(object sender, EventArgs e)
    {
        currentTB = (TextBox)sender;
    }

问候

约瑟夫

编辑:TextBox子类的解决方案:

class TextBoxIM: TextBox{
    public static TextBox tb;
    protected override void OnGotFocus (EventArgs e)
    {
        tb=this;
        base.OnGotFocus (e);
    }
}
...
private void btnOK_Click (object sender, System.EventArgs e)
{    
    string sName="";
    foreach(Control c in this.Controls){
        if (c.GetType()==typeof(TextBoxIM)){
            sName=c.Name;
            break; //we only need one instance to get the value
        }
    }
    MessageBox.Show("Last textbox='"+sName+"'");
    }

然后,不要使用TextBoxIM来放置TextBox。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM