自己写了个监控键盘按键的小程序。
在界面上实时显示按下的键,但是想实现程序的开机自启如何实现呢。
开机自启动一种是在windows的“C:\Users\用户名\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup”家快捷方式。但是这种方法自测有时候不成功。
还有就是写注册表。
主要记录一下这个方法。
1、注册开机启动
//程序的名称
private const string SoftWareName = "Raink.KeyPressedView";
private void SetStartWithStartUp()
{
string path = Application.ExecutablePath;
// 针对当前用户添加注册表启动项
RegistryKey rk = Registry.CurrentUser;
try
{
//注册表位置
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
// 检测是否之前有设置自启动了,如果设置了,就看值是否一样
string old_path = (string)rk2.GetValue(SoftWareName);
if (!path.Equals(old_path))
{
//写入值
rk2.SetValue(SoftWareName, path);
MessageBox.Show("设置开机自启成功", "KeyPressedView");
}
else
{
MessageBox.Show("已设置过开机自启", "KeyPressedView");
}
rk2.Close();
rk.Close();
}
catch (Exception e)
{
MessageBox.Show($"开机自启动设置失败:{e}", "KeyPressedView");
}
}
- 取消开机自启
private void CancelStartWithStartUp()
{
string path = Application.ExecutablePath;
RegistryKey rk = Registry.CurrentUser;
try
{
//相同的注册表位置
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
//获取现有值
string old_path = (string)rk2.GetValue(SoftWareName);
//删除值
rk2.DeleteValue(SoftWareName, false);
MessageBox.Show("已取消开启自启", "KeyPressedView");
rk2.Close();
rk.Close();
}
catch (Exception e)
{
MessageBox.Show($"未能正常取消开机自启:{e}", "KeyPressedView");
}
}