简体   繁体   English

防止按钮聚焦

[英]Prevent button getting focus

I have a solution with several forms, each may have TextBox's/controls and a button to show the SIP (the bottom bar is hidden). 我有几种形式的解决方案,每种形式都有TextBox的控件/控件和一个用于显示SIP的按钮(底部栏处于隐藏状态)。

When the user clicks my SIP button, the SIP is enabled but the focus is now the button. 当用户单击我的SIP按钮时,将启用SIP,但现在焦点是按钮。 I want the user to click the button - the SIP to display but the focus to remain on the control that had the focus before the user clicked the button. 我希望用户单击按钮-显示SIP,但将焦点保留在用户单击按钮之前具有焦点的控件上。 Does anyone know how to do this? 有谁知道如何做到这一点? Thanks. 谢谢。

Instead of using an standard button, you can create a custom one by deriving from the Control class and overriding the OnPaint method. 可以使用Control类并覆盖OnPaint方法来创建自定义按钮,而不是使用标准按钮。 A control created this way will not claim the focus by default when treating the Click event (tested on VS2008 netcf 2.0). 默认情况下,在处理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);
    }
}

The solution of nathan will work also for Compact Framework or native Windows Mobile applications. nathan的解决方案也将适用于Compact Framework或本机Windows Mobile应用程序。 In the textbox GotFocus set a global var and use this in the buttons click event to set the focus back to the last active textbox: 在文本框中,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;
    }

regards 问候

Josef 约瑟夫

Edit: Solution with subclass of TextBox: 编辑: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+"'");
    }

Then, instead of placing TextBox use TextBoxIM. 然后,不要使用TextBoxIM来放置TextBox。

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

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