.NET调用Windows API隐藏控制台程序运行的窗口,并设置开机自启动
首先编写功能代码类,如下
说明:在设置开机自启动还是有一点问题,前提是用户必须具有管理员权限,不然操作不了注册表。
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Windows.Forms;
5 using Microsoft.Win32;
6 using System.Runtime.InteropServices;
7
8 ///
9 /// Visual Studio 2008 编写
10 namespace Utilities
11 {
12 public class windowUtilities
13 {
14 [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
15 private static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
16 [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
17 private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
18 /// <summary>
19 /// 设置窗体隐藏
20 /// </summary>
21 /// <param name="consoleTitle">窗体的Title</param>
22 public static void WindowHide(string consoleTitle)
23 {
24 IntPtr a = FindWindow("ConsoleWindowClass", consoleTitle);
25 if (a != IntPtr.Zero)
26 ShowWindow(a, 0);//隐藏窗口
27 else
28 throw new Exception("can't hide console window");
29 }
30 /// <summary>
31 /// 设置程序开机自启动
32 /// </summary>
33 public static void SetAutoStart()
34 {
35 string R_startPath = Application.ExecutablePath;
36 RegistryKey rk_local = Registry.LocalMachine;
37 RegistryKey rk_run = rk_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
38 //rk_run.DeleteSubKey("ConsoleApp_yh", false);
39
40 rk_run.SetValue("ConsoleApp_yh",R_startPath);
41 rk_run.Close();
42 rk_local.Close();
43 }
44 }
45 }
调用形式如下:
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
5 using System.Runtime.InteropServices;
6 using System.IO;
7
8
9
10 namespace Test
11 {
12 class Program
13 {
14
15
16 static void Main(string[] args)
17 {
18 Console.Title = "tohidewindow"; //为控制台窗体指定一个标题,便于定位和区分
19 Utilities.windowUtilities.WindowHide("tohidewindow");
20 //隐藏这个窗口
21 Utilities.windowUtilities.SetAutoStart();//设置开机自启动
22 Console.ReadKey();
23 }
24 }
25 }