簡體   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