简体   繁体   English

当用户单击asp按钮时,如何模拟键盘按钮的按下?

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

Say for example I have an asp button: 比如说我有一个asp按钮:

<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). 长答案是...它完全取决于您的软件堆栈(例如,您正在运行的Web服务器)。

Under IIS your code will run but have no effect. 在IIS下,您的代码将运行,但无效。 IIS (I believe) runs as a service that is not allowed to have UI interactivity. IIS(我相信)是作为不允许具有UI交互性的服务运行的。

If you are running using the VS dev server then your code will probably work on your local machine only. 如果您使用VS dev服务器运行,则您的代码可能仅在本地计算机上工作。

Even if you find a production-ready web server that allows UI interaction to host your page, your code-behind runs on the SERVER. 即使您找到了可以通过UI交互来托管页面的可投入生产的Web服务器,您的后台代码也会在SERVER上运行。 There is no client-side web browser API for injecting keypresses into the system. 没有用于将按键输入到系统中的客户端Web浏览器API。

Try this - JS code borrowed from this thread 试试这个-从这个线程借来的JS代码

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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