简体   繁体   中英

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).

When the user clicks my SIP button, the SIP is enabled but the focus is now the button. 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. 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. A control created this way will not claim the focus by default when treating the Click event (tested on 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. 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:

    //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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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