C#控制台程序启动后最小化或者隐藏小黑板

最近在项目中用到的,实在没有兴趣去写成Windows Service方式,只能最简单的Console方式了!再在特定条件下启动后能够后台执行或者最小化到任务栏而不会挡在屏幕中央!基本思路是P/Invoke方式:

1 using System;
2  using System.Runtime.InteropServices;
3 using System.Threading;
4
5
6 class TestClass
7 {
8 static void Main(string[] args)
9 {
10 try
11 {
12 new TestClass();
13 }
14 catch (Exception)
15 {
16
17 throw;
18 }
19 }
20
21
22 [DllImport("User32.dll", EntryPoint = "FindWindow")]
23 private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
24
25 [DllImport("user32.dll", EntryPoint = "FindWindowEx")] //找子窗体
26 private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
27
28 [DllImport("User32.dll", EntryPoint = "SendMessage")] //用于发送信息给窗体
29 private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
30
31 [DllImport("User32.dll", EntryPoint = "ShowWindow")] //
32 private static extern bool ShowWindow(IntPtr hWnd, int type);
33
34 public TestClass()
35 {
36 Console.Title = "MyConsoleApp";
37 IntPtr ParenthWnd = new IntPtr(0);
38 IntPtr et = new IntPtr(0);
39 ParenthWnd = FindWindow(null, "MyConsoleApp");
40
41 ShowWindow(ParenthWnd, 2);//隐藏本dos窗体, 0: 后台执行;1:正常启动;2:最小化到任务栏;3:最大化
42
43 //作自己的事情
44 Thread.Sleep(3000);
45
46 Console.Write("Exit");
47
48 }
49 }
posted @ 2011-03-08 22:05  pccai  阅读(13064)  评论(2编辑  收藏  举报