2013-05-14 286 views
2

我想在某些事件上按下Shift + Tab,我爲此目的使用System.Windows.Forms.SendKeys.Send,但它不起作用,我嘗試了下面的方法來調用該函數。SendKeys.Send功能不起作用

System.Windows.Forms.Application.DoEvents(); 
       SendKeys.Send("{+(Tab)}"); 

System.Windows.Forms.Application.DoEvents(); 
       SendKeys.Send("+{Tab}"); 

System.Windows.Forms.Application.DoEvents(); 
       SendKeys.Send("{+}{Tab}"); 

System.Windows.Forms.Application.DoEvents(); 
       SendKeys.Send("+{Tab 1}"); 

有人能告訴我什麼是正確的方法嗎?

+2

不工作怎麼樣?沒有開火?你如何證實他們並沒有真正開火? 「不工作」是你可以描述問題的最糟糕的方式。 – tnw 2013-05-14 12:31:33

+0

_it不是你的意思_你是怎麼測試它的? – gideon 2013-05-14 12:31:55

+0

+ {TAB}是正確的語法,+ {TAB 1}也應該有效。其他人會做別的。 ('+(Tab)'會同時發送班次,'T','A'和'B'鍵;'{+} {Tab}'會發送'+'鍵,後跟'Tab'。它是正確的假設調用'.Focus()'你想設置焦點的元素不是一個選項? – drf 2013-05-14 12:38:17

回答

0

它沒有做任何事情或將輸入發送到您不想編輯的控件中?請檢查此代碼是否先被調用,並且不要忘記在SendKeys之前手動將焦點放在目標控件上,以確保它將接收您的密鑰。

2

正確語法如下:

SendKeys.Send("+{Tab}"); 

在光你的評論,你試圖實現按Shift+Tab來控制字段之間的循環,注意,這可以更可靠地不仿效鍵來完成。這樣可以避免出現問題,例如,其他窗口有重點。

以下的方法將模擬Shift_Tab的行爲,通過標籤循環以相反的順序停止:

void EmulateShiftTab() 
{ 
    // get all form elements that can be focused 
    var tabcontrols = this.Controls.Cast<Control>() 
      .Where(a => a.CanFocus) 
      .OrderBy(a => a.TabIndex); 

    // get the last control before the current focused element 
    var lastcontrol = 
      tabcontrols 
      .TakeWhile(a => !a.Focused) 
      .LastOrDefault(a => a.TabStop); 

    // if no control or the first control on the page is focused, 
    // select the last control on the page 
    if (lastcontrol == null) 
      lastcontrol = tabcontrols.LastOrDefault(); 

    // change focus to the proper control 
    if (lastcontrol != null) 
      lastcontrol.Focus(); 
} 

編輯

刪除的文本將通過控制循環按照相反的順序(模擬shift + Tab),但是這樣做更合適,使用內置的 HOD。以下方法將模擬Shift_Tab的行爲,以相反順序循環制表符停止。

void EmulateShiftTab() 
{ 
    this.SelectNextControl(
     ActiveControl, 
     forward: false, 
     tabStopOnly:true, 
     nested: true, 
     wrap:true); 
}