Start the screensaver from code in VB6

By | 2017-05-20

Nothing magical here. Just using the Windows API to start the screensaver on demand from code in Windows.

Let’s say you have a, err, questionable, process running a computer. Hey, I don’t judge. I like a good game of solitaire at work, too. Let us also pretend that your boss is not so keen on having you playing cards while you are supposed to be working.

You could potentially create a small, one-form app, with just a button on it. Make stay on top of all other windows, and park it in the corner of the screen. When you hear the boss coming, poke the button, and your screen saver instantly activates.

The function and API is shown below. Simply drop this in a module in your app, and you should be good to go.

Private Declare Function GetDesktopWindow Lib _
"user32" () As Long

Private Declare Function SendMessage Lib "user32" _
   Alias "SendMessageA" (ByVal hwnd As Long, ByVal _
   wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) _
   As Long

Private Const WM_SYSCOMMAND As Long = &H112&
Private Const SC_SCREENSAVE As Long = &HF140&

Public Function StartScreenSaver() As Boolean

   Dim lDesktopWindow As Long
   Dim lRet As Long

   On Error GoTo ErrorHandler
   lDesktopWindow = GetDesktopWindow()
   lRet = SendMessage(lDesktopWindow, WM_SYSCOMMAND, _
   SC_SCREENSAVE, 0)

   StartScreenSaver = (lRet = 0)

ErrorHandler:

End Function

From your form, you can call it as shown below. I told you it was easy!

ret = StartScreenSaver

Note:

Yes, this works in all versions of Windows, up to and including Windows 10.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.