2013-05-14 293 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); 
}