C# 设置和启动Windows屏保程序
- 其他代码
- 2024-11-25
- 208热度
- 0评论
设置电脑屏保参数,在个性化设置>锁屏界面>屏幕保护程序设置进行调节和设置。设置完成后参数会写入注册表,电脑会根据注册表中设置的参数启动屏保程序。我们也可以使用程序直接设置注册表屏保参数,启动我们自定义屏保程序。
屏保注册表位置:计算机HKEY_CURRENT_USERControl PanelDesktop
屏保注册表参数如下
SCRNSAVE.EXE:默认屏保程序,我们可将此键值设置为我们制作的程序(程序后缀为.scr)
ScreenSaveActive:屏保状态,1为启动,0为关闭
ScreenSaveTimeout:屏幕保护程序启动前系统的空闲事件,单位为秒,默认为900(15分钟)
ScreenSaverIsSecure:默认参数为0,标识不需要用户密码登录即可启动屏保
C#代码启动自定义屏保
internal class ComputerHelper
{
[DllImport("user32.dll")]
private static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);
private const int HWND_BROADCAST = 0xffff;
private const int WM_SYSCOMMAND = 0x112;
private const int SC_SCREENSAVE = 0xf140;
/// <summary>
/// 启动屏幕程序
/// </summary>
public static void ScreenSaveStart()
{
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_SCREENSAVE, 0);
}
}
public partial class MainWindow : Window
{
private string screenSaver = "D:\Test.scr";
public MainWindow()
{
InitializeComponent();
}
#region Methods
/// <summary>
/// 更新屏保注册表参数
/// </summary>
private void UpdateScreenSaverRegist()
{
//获取user根项
RegistryKey user = Registry.CurrentUser;
//打开desktop项
RegistryKey desktop = user.OpenSubKey("Control Panel\Desktop", true);
if(desktop != null)
{
//设置屏保程序位置
desktop.SetValue("SCRNSAVE.EXE", screenSaver);
//是否启动屏保 0:不启动 1:启动
desktop.SetValue("ScreenSaveActive", "1");
//退出屏保后是否需要登录 0:不需要 1:需要
desktop.SetValue("ScreenSaverIsSecure", "1");
//电脑无操作后启动屏保时间
desktop.SetValue("ScreenSaveTimeout", "60");
}
}
#endregion
private void btnSetScreenSaver_Click(object sender, RoutedEventArgs e)
{
try
{
UpdateScreenSaverRegist();
ComputerHelper.ScreenSaveStart();
}
catch (Exception ex)
{
MessageBox.Show($"设置屏保失败->{ex.Message}");
}
}
}