2012-03-23 72 views
1

我有一個用戶控件,它的行爲與浮動控件一樣,並且我希望在其可見時將製表順序僅限制到我的用戶控件。基本上我需要的是有一個像無邊界Form行爲的控制。其實這是一個Form,但我需要在MainForm窗口中保留焦點,所以我不得不將它更改爲UserControl將製表符順序限制爲單個用戶控件

所以,想象一個Form A(MainForm的),和我的UserControl B. B是A的子控件假設A型有一個按鈕和一個文本框,並控制B也有一個按鈕和一個文本框。該currenly發生的secuence如下

什麼目前發生(自然tab順序行爲):

當只有一個是可見的(B是不可見):

1. The user manually focuses A textbox 
2. Press tab key 
3. A button is focused 

當A可見並且B可見時:(自然Tab鍵順序鍵如下):

1. The user manually focuses B textbox 
2. Press tab key 
3. B button is focused 
4. Press tab key 
5. A textbox is focused 
6. Press tab key 
7. A button is focused 

我需要什麼(我需要改變我的用戶控制,以保持對焦):

我真正需要的是,B控制保留它裏面 Tab鍵順序,所以我需要的是與當B控制是可見的:

1. The user manually focuses B texbox 
2. Press tab key 
3. B button is focused 
4. Press tab key 
5. B textbox is focused 
+0

你不應該這樣做 - 它打破了鍵盤只有用戶的導航能力(如視障人) – 2012-03-23 12:36:30

+0

我** **需要做到這一點。我的用戶控件表現爲浮動控件。目前的行爲很奇怪。 – 2012-03-23 12:39:28

+0

當然,你可以在模態對話框中顯示你的用戶控件?這聽起來像你想要複製的東西。 – 2012-03-23 12:43:30

回答

0

最後我解決了這個問題,包括在括號下面的代碼t控制:

private int WM_KEYDOWN = 0x100; 

    public override bool PreProcessMessage(ref Message msg) 
    { 
     Keys key = (Keys)msg.WParam.ToInt32(); 

     if (msg.Msg == WM_KEYDOWN && key == Keys.Tab) 
     { 
      if (itemSearchControl.Visible) 
      { 
       bool moveForward = !IsShiftKeyPressed(); 
       bool result = itemSearchControl.SelectNextControl(itemSearchControl.ActiveControl, true, true, true, true); 
       return true; 
      } 
     } 

     return base.PreProcessMessage(ref msg); 
    } 
0

您可以覆蓋控制KeyDown事件和手動移動焦點到應該接收焦點的控制。

除此之外,我同意威爾·休斯,它可能會破壞導航...

0

我假設你有一些按鈕,按下該切換您的B的用戶控制的可見性。如果它是可見的並且有焦點,那麼它保持焦點。只有當你將它切換到隱藏狀態時,它纔會失去焦點。如果是這樣的話,你可以嘗試在你的表單驗證碼,這將讓你的焦點在用戶控件,除非你隱藏的用戶控件:

// store when we last clicked the toggle B user control visibility 
private Stopwatch _sinceLastMouseClick; 

public Form1() 
{ 
    InitializeComponent(); 
    // instantiate the stopwatch and start it ticking 
    _sinceLastMouseClick = new Stopwatch(); 
    _sinceLastMouseClick.Start(); 
} 

是切換你的浮動B控制的單擊處理能見度按鈕:

private void btnToggleBUserControlVisibility_Click(object sender, EventArgs e) 
{ 
    // reset the stopwatch because we just clicked it 
    _sinceLastMouseClick.Restart(); 
    myUserControl1.Visible = !myUserControl1.Visible; 
} 

在你父母的表格,辦理浮動用戶控件的Leave事件:

private void myUserControl1_Leave(object sender, EventArgs e) 
{ 
    // see if the mouse is over the toggle button 
    Point ptMouse = System.Windows.Forms.Control.MousePosition; 
    Point ptClient = this.PointToClient(ptMouse); 
    // if the mouse is NOT hovering over the toggle button and has NOT just clicked it, 
    // then keep the focus in the user control. 
    // We use the stopwatch to make sure that not only are we hovering over the button 
    // but that we also clicked it, too 
    if (btnToggleBUserControlVisibility != this.GetChildAtPoint(ptClient) || 
     _sinceLastMouseClick.ElapsedMilliseconds > 100) 
    { 
     myUserControl1.Focus(); 
    } 
}