4

I want to simulate WindowsKey + L (The short cut to lock the console) in visual basic and bind it to a function. So when this function is called it will lock the console. Can I do this?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • There was a VBA tag already, and that tells us pretty much everything we need to know. As long as it's not VB.NET, you'd do this the same way in VBA as you would in VB 6. – Cody Gray - on strike Aug 11 '12 at 03:28
  • Related question in [.NET](http://stackoverflow.com/questions/11812562/how-to-lock-windows-like-windows-l-from-net) and [C/C++](http://stackoverflow.com/questions/4259571/how-to-lock-the-screen-in-windows) All with exactly the same answers! – Deanna Aug 14 '12 at 08:20

1 Answers1

14

Simulating the hotkey is the wrong approach. All you need to do is call the LockWorkStation function. This has the same result as pressing Ctrl+Alt+Del and selecting "Lock Workstation", or using the Win+L hotkey, except that you can do it programmatically through code.

To call this function from a VB application, you'll need to write a declaration, like so:

Private Declare Function LockWorkStation Lib "user32.dll" () As Long

You'll want to place that declaration at the top of your module file, before any procedures are defined. Then, inside one of the procedures, you can call the function. For example:

Private Sub LockComputer()
    LockWorkStation
End Sub

Even better code would check the return value of LockWorkStation for an error code. A return value of 0 indicates an error. The standard way of checking for Win32 errors in VB, Err.LastDllError, will give you more information about what exactly went wrong.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • 3
    + 1 Yup The API is the best way to Go. However one suggestion. I have not tested it but VBA will not let you use `Private Sub Lock()` I believe 'Lock' is a reserved word. Maybe changing it to something like `Private Sub LockPC()` would help? – Siddharth Rout Aug 11 '12 at 04:13
  • Yup just tested it. It will not let you use `Lock`. Vb6 will also not let you use it. – Siddharth Rout Aug 11 '12 at 04:14
  • Blah, that's what I get for posting untested code! Thanks for the heads-up. – Cody Gray - on strike Aug 11 '12 at 04:18
  • Is there any reason you wrap the API call in a separate Sub or Function anyway? I can't see one. If you really wanted a different name `Declare` has an `Alias` clause. – Bob77 Aug 11 '12 at 18:20
  • Nope, just an example that shows it's called like a regular function. There's no good reason to wrap it up. – Cody Gray - on strike Aug 12 '12 at 04:47