3

我想在某个事件上按 Shift + Tab,我正在System.Windows.Forms.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}");

有人能告诉我什么是正确的方法吗?

4

2 回答 2

3

The proper syntax is:

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

In light of your comment that you are trying to implement pressing Shift+Tab to cycle between control fields, note that this can be done more reliably without emulating keys. This avoids issues where, for instance, another window has focus.

The following method will emulate the behavior of Shift_Tab, cycling through tab stops in reverse order:

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();
}

Edit

The deleted text will cycle through controls in reverse order (emulating shift+Tab), but this is more properly done with with the built-in Form.SelectNextControl method. The following method will emulate the behavior of Shift_Tab, cycling through tab stops in reverse order.

void EmulateShiftTab()
{
    this.SelectNextControl(
        ActiveControl,
        forward: false,
        tabStopOnly:true, 
        nested: true, 
        wrap:true);
}
于 2013-05-14T13:05:26.360 回答
0

它是什么都不做或将输入发送到您不想被编辑的控件中?检查是否首先调用了此代码,并且不要忘记在 SendKeys 之前手动关注目标控件,以确保它会收到您的密钥。

于 2013-05-14T12:31:19.683 回答