Click here to Skip to main content
16,016,759 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to assign it to one of my additional keyboard keys, I know how to assign an exe to one of my additional keyboard keys.

What I have tried:

With the code below it starts the screensaver and when I move the mouse the screensaver stops but the screen is shown as my work in the desktop for 1 second then the screen locks, moving
LockWorkStation();
up 1 or 2 lines didn't help much as the screen locks but no screensaver runs.

using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32;


namespace LockAndStartScreenSaver
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (screenSaverKey != null)
            {
                string screenSaverFilePath = screenSaverKey.GetValue("SCRNSAVE.EXE", string.Empty).ToString();
                if (!string.IsNullOrEmpty(screenSaverFilePath) && File.Exists(screenSaverFilePath))
                {
                    Process screenSaverProcess = Process.Start(new ProcessStartInfo(screenSaverFilePath, "/s"));  // "/s" for full-screen mode
                    screenSaverProcess.WaitForExit();  // Wait for the screensaver to be dismissed by the user
                    LockWorkStation();
                }
            }
        }


        [DllImport("user32")]
        static public extern void LockWorkStation();


        static RegistryKey screenSaverKey = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop");
    }
}
Posted
Updated 6-Apr-23 5:33am
Comments
0x01AA 6-Apr-23 6:55am    
Maybe this helps with some ideas: Programmatically Turning on the Screen Saver[^]
John Smith 27 6-Apr-23 7:03am    
It didn't help, sorry.
0x01AA 6-Apr-23 7:45am    
Did you try it? If yes what is the problem?
John Smith 27 6-Apr-23 7:50am    
Actually it works like magic I'm sorry I didn't understand it first, submit as an answer plz.
John Smith 27 6-Apr-23 7:54am    
But the application keeps running and doesn't exit after login, how to fix that?

See all the coments...

Looks like PostMessage instead of SendMessage was the solution and solved by OP.

Comment snippet:
Try something like this. I will not google it for you ;) And of course set the right parameters where I simply put a 0.

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

private void button1_Click(object sender, EventArgs e)
{
PostMessage(new IntPtr(), 0, (IntPtr)0, (IntPtr)0);
}


This based on this CP Article: Programmatically Turning on the Screen Saver[^]

[Edit]
Correction from OP:

PostMessage(
new HandleRef(null, new IntPtr((int)SpecialHandles.HWND_BROADCAST)),
WM_SYSCOMMAND,
new IntPtr( SC_SCREENSAVE),
new IntPtr( 0));
 
Share this answer
 
v2
Comments
John Smith 27 6-Apr-23 12:10pm    
Accepted but plz change the arguments like the ones I made in my answer, the ones in your answer don't work, these work:

PostMessage(
new HandleRef(null, new IntPtr((int)SpecialHandles.HWND_BROADCAST)),
WM_SYSCOMMAND,
new IntPtr( SC_SCREENSAVE),
new IntPtr( 0));
0x01AA 6-Apr-23 12:20pm    
I have added your correction. Thanks for accepting the answer.
This is what the user named: 0x01AA suggested in a link and comments and I changed stuff in it, works like magic:

using System;
using System.Runtime.InteropServices;

namespace ScreenSaverAndLockScreen
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            TurnOnScreenSaver();
        }

        public const uint WM_SYSCOMMAND = 0x112;
        public const uint SC_SCREENSAVE = 0xF140;


        [DllImport("User32.dll")]
        static extern bool PostMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam);


        public enum SpecialHandles
        {
            //HWND_DESKTOP = 0x0,
            HWND_BROADCAST = 0xFFFF
        }

        public static void TurnOnScreenSaver()
        {
            PostMessage(
                new HandleRef(null, new IntPtr((int)SpecialHandles.HWND_BROADCAST)),
                WM_SYSCOMMAND,
                new IntPtr( SC_SCREENSAVE),
                new IntPtr( 0));
        }
    }
}
 
Share this answer
 
v4
Comments
0x01AA 6-Apr-23 9:08am    
Wait wait... Don't post things like this as an answer. There are crazy nit picking members around here which will downvote something like that (as you can see :( ).
Use 'improve question' in your original question to post information like this.

And btw. looks like you did not replaced SendMessage by PostMessage....
PIEBALDconsult 6-Apr-23 10:50am    
Testify!
0x01AA 6-Apr-23 10:53am    
What exactly? Nit pickings or Send vs. Post ;P :D
This isn't a perfect way but it worked for me, I run the screensaver and hide every screen the user has with a black borderless maximized topmost form and then when the user logs back in detect this event and exit the application and the black forms exit too, it works for me and I'm using it as I can't find another option, I keep it here for the benefits of others to learn stuff from it...

using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Collections.Generic;


namespace LockAndStartScreenSaver
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {



            Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);


            if (screenSaverKey != null)
            {
                string screenSaverFilePath = screenSaverKey.GetValue("SCRNSAVE.EXE", string.Empty).ToString();
                if (!string.IsNullOrEmpty(screenSaverFilePath) && File.Exists(screenSaverFilePath))
                {
                    Process screenSaverProcess = Process.Start(new ProcessStartInfo(screenSaverFilePath, "/s"));  // "/s" for full-screen mode


                    foreach (Screen s in Screen.AllScreens)
                    {
                        lstForms.Add(new FormMainHide(s.Bounds.X, s.Bounds.Y));//FormMainHide is a borderless topmost maximized black form to hide the screens
                        lstForms[lstForms.Count - 1].Show();
                    }

                    screenSaverProcess.WaitForExit();  // Wait for the screensaver to be dismissed by the user

                    LockWorkStation();

                    Application.Run();
                }
            }
        }







        static void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
        {
            //if (e.Reason == SessionSwitchReason.SessionLock)
            //{
                //I left my desk
                //Console.WriteLine("I left my desk");
            //}
            else if (e.Reason == SessionSwitchReason.SessionUnlock)
            {
                //I returned to my desk
                Application.Exit();
            }
        }








        [DllImport("user32")]
        static public extern void LockWorkStation();


        static List<FormMainHide> lstForms = new List<FormMainHide>();

        static RegistryKey screenSaverKey = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop");
    }
}
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900