您的位置:首页 > 编程语言 > C#

C#中实现程序开机自启动 三种方式

2009-07-23 16:18 561 查看
1、首先想到写注册表,关键代码如下:

1

public void RunWhenStart(bool Started, string name, string path)
2

{
3

RegistryKey HKLM = Registry.LocalMachine;
4

RegistryKey Run = HKLM.CreateSubKey(@"SOFTWARE//Microsoft//Windows//CurrentVersion//Run/");
5

if (Started == true)
6

{
7

try
8

{
9

Run.SetValue(name, path);
10

HKLM.Close();
11

}
12

catch (Exception)
13

{
14

MessageBox.Show("注册表修改错误(开机自启未实现)");
15

}
16

}
17

else
18

{
19

try
20

{
21

if (Run.GetValue(name) != null)
22

{
23

Run.DeleteValue(name);
24

HKLM.Close();
25

}
26

else
27

return;
28

}
29

catch (Exception e)
30

{
31

ExceptionTransact.WriteErrLog(base.GetType().Name, e.Message);
32

//
33

}
34

}
35

}
用了一段时间后,发现问题出来了:公司市场部的电脑,用户没有写注册表的权限,所以此功能无效,只能另想办法。

本来考虑写一个系统服务,由系统服务启动话务系统,不过在实现中遇到了问题:话务系统单独启动没有问题,由系统服务启动时在Application.Run(new MainForm());处一直报空引用错误,而调试中new MainForm()并不为空。由于此问题无法解决,无奈之下改用其它办法。

2、桌面生成快捷方式,然后把快捷方式复制到用户启动文件夹:

1 public static void Main()
2 {
3 WshShell shell = new WshShell();
4 //创建可执行文件快捷方式到桌面
5 IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(
6 Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) +
7 "//" + "XX话务系统客户端.lnk"
8 );
9 shortcut.TargetPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
10 shortcut.WorkingDirectory = System.Environment.CurrentDirectory;
11 shortcut.WindowStyle = 1;
12 shortcut.Description = "XX话务系统客户端";
13 shortcut.IconLocation = System.Environment.CurrentDirectory + "//" + "phone9.ico";
14 shortcut.Save();
15 Application.EnableVisualStyles();
16 Application.SetCompatibleTextRenderingDefault(false);
17 // get the name of our process
18 MainForm mf = new MainForm();
19 string proc = Process.GetCurrentProcess().ProcessName;
20 // get the list of all processes by that name
21 Process[] processes = Process.GetProcessesByName(proc);
22 // if there is more than one process
23 if (processes.Length > 1)
24 {
25 MessageBox.Show("程序已经运行!");
26 return;
27 }
28 else
29 Application.Run(mf);
30 }

1 private void checkBox1_CheckedChanged(object sender, EventArgs e)
2 {
3 //获取当前系统用户启动目录
4 string StartupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Startup);
5 //获取当前系统用户桌面目录
6 string desktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
7 if (checkBox1.Checked)
8 {
9 //获取可执行文件快捷方式的全部路径
10 string exeDir = desktopPath + "//XX话务系统客户端.lnk";
11 //把程序快捷方式复制到启动目录
12 System.IO.File.Copy(exeDir, StartupPath + "//XX话务系统客户端.lnk", true);
13 }
14 //RunWhenStart(true, Application.ProductName, Application.StartupPath + @"/XX话务系统客户端.exe");
15 else
16 {
17 System.IO.File.Delete(StartupPath + "//XX话务系统客户端.lnk");
18 }
19 //RunWhenStart(false, Application.ProductName, Application.StartupPath + @"/XX话务系统客户端.exe");
20 }

现在系统服务启动应用程序的问题还在解决中.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: