0

Is there any way to press windows+prtscreen programitically with the help of javascript in nodejs. I want to press these two keys programitically in my project using onclick=""; and then the function which will do this.

1 Answers1

0

If I get you right, you want to press the two keys and execute a function by doing so? If so, you may use another event handler as onclick is used for mouse input only. You can look into KeyboardEvent handler here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.

In vanilla JS you can check what keys are pressed with

function myKeyPress(e){
  var keynum;

  if(window.event) { // IE                  
    keynum = e.keyCode;
  } else if(e.which){ // Netscape/Firefox/Opera                 
    keynum = e.which;
  }

  alert(String.fromCharCode(keynum));
}

and

<input type="text" onkeypress="return myKeyPress(event)" />

Then just execute your code, if the certain combination is pressed. You can get the keycode for every key on this website: https://keycode.info/.

For multiple key detection you can also check out this elaborative thread here: How to detect if multiple keys are pressed at once using JavaScript?.

In this case, it would look similar to this:

function win_prin(selkey){
    var alias = {
        "win":  91,
        "print": 44
    };

    return key[selkey] || key[alias[selkey]];
}

function win_prins(){
    var keylist = arguments;

    for(var i = 0; i < keylist.length; i++)
        if(!win_prin(keylist[i]))
            return false;

    return true;
}

Then you can call the function with:

if(win_prins('win', 'print')){
    /* do something, if the two keys are pressed */
}
christheliz
  • 176
  • 2
  • 15
  • Yes this is exactly what i want to do – Yash Singhal Jul 10 '21 at 19:21
  • Let me know if the answer helped. An upvote and accepting the answer would be much appreciated:) – christheliz Jul 10 '21 at 19:33
  • Can you please write the code for windows + PrintScreen multiple keys also. – Yash Singhal Jul 10 '21 at 19:34
  • I added an example of how to do it. I didn't compile it, but you should finish it from here on easily – christheliz Jul 10 '21 at 19:46
  • This code detects key events that were pressed by the user, but the questions asks how to trigger a prtscrn from the nodejs program without the user pressing keys. It appears this answer is not addressing what the question is asking. – jfriend00 Jul 11 '21 at 04:00
  • The question was to press two buttons and execute a function. It was clarified in the first sentence of my answer, which is a reply to his first comment – christheliz Jul 11 '21 at 08:37