Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SendKeys.Send function not working

Tags:

c#

sendkeys

I want to press Shift + Tab on some event , I am using System.Windows.Forms.SendKeys.Send for that purpose but it is not working , I tried below ways to call the function.

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

Can someone tell me what is the right way ?

like image 334
Sagar Avatar asked Aug 09 '26 05:08

Sagar


1 Answers

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);
}
like image 157
drf Avatar answered Aug 10 '26 18:08

drf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!