Powershell – capture mouse click event inside a powershell console


I’m trying to do some trick with Powershell. I want to write a script and that script can listen to the mouse events (click, move, etc) inside the powershell console.

For example, while my script is active, when I click the mouse inside the powershell console, the console can output the position of my cursor.

Is it possible? If possible, how?

Thanks in advance.


I’ve found that it’s possible to do this using the following:

Which returns a string of the currently pressed mouse buttons. We poll this and [System.Windows.Forms.Cursor]::Position as per WorWin to keep track of where the mouse is and what buttons are pressed.

Keeping track of where the mouse is inside of the console window is a bit tricky, though. I personally use a custom class for this.

To get the Powershell console window:

Now, $win.bounds gives us the outer bounds of the console window, so if we want to find which buffercell the cursor is in we’re going to have to do some work on our bounds.

This gives us the offsets we need to get the inner bounds of the window. From here we can get our relative location on the window.

Now we can convert our mouse position to buffer cell position.

You’ll have to use $win.update() every time you check. You can also use $win.isforeground and [Windows.Forms.UserControl]::MouseButtons -match "Left" to only check when the console window is clicked as well.


Powershell – capture mouse click event inside a powershell console by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply