简体   繁体   中英

How do I simulate keyboard button press when the user clicks on asp button?

Say for example I have an asp button:

<asp:Button id="btnCustomDropDown"
Text="*"
OnClick="txtOutputRating_btnPressed" 
runat="server"/>

When the user presses that button, I want a keyboard button to be pressed. For example the down key on the keyboard. I was thinking of something like this on the backend. Is this possible?

void txtOutputRating_btnPressed(Object sender, EventArgs e)
    {
        System.Windows.Forms.SendKeys.Send("{DOWN}");
    }

The short answer is NO - it won't work.

The long answer is... It depends entirely on your software stack (eg, what web server you are running).

Under IIS your code will run but have no effect. IIS (I believe) runs as a service that is not allowed to have UI interactivity.

If you are running using the VS dev server then your code will probably work on your local machine only.

Even if you find a production-ready web server that allows UI interaction to host your page, your code-behind runs on the SERVER. There is no client-side web browser API for injecting keypresses into the system.

Try this - JS code borrowed from this thread

<asp:Button OnClientClick="pressDown();" />

<script>
    var keyboardEvent = document.createEvent("KeyboardEvent");
    var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";

    function pressDown() {
        keyboardEvent[initMethod](
           "keydown", // event type : keydown, keyup, keypress
            true, // bubbles
            true, // cancelable
            window, // viewArg: should be window
            false, // ctrlKeyArg
            false, // altKeyArg
            false, // shiftKeyArg
            false, // metaKeyArg
            40, // keyCodeArg : unsigned long the virtual key code, else 0
            0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
        );

        document.dispatchEvent(keyboardEvent);
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM