获取弹出框的句柄,关闭弹出框

     大家可能有过这样的需求,有的弹出框可能需要手动关闭,这样非常麻烦,我参考相关资料,用C# 程序自动关闭弹出框的例子,供大家参考

 1 //获取弹出框的句柄,并隐藏函数。
 2 using System.Runtime.InteropServices;//这个是必须的命名空间。
 3 class SearchWindow
 4     {
 5 
 6         private const int WM_Close = 0x0010;
 7         [DllImport("User32.dll ", EntryPoint = "FindWindow")]
 8         private static extern IntPtr FindWindow(string lpClassName,
 9         string lpWindowName);
10         [DllImport("user32.dll", EntryPoint = "SendMessageA")]
11         private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, string lParam);
12         public SearchWindow()
13         {
14                 
15         }
16         public void closeWindow(string lpClassName, string lpWindowName)
17         {
18             
19            IntPtr  Mhandle= FindWindow(null, lpWindowName);
20            if (Mhandle != IntPtr.Zero)
21                SendMessage(Mhandle, WM_Close, IntPtr.Zero, null);
22            else
23            {
24                return;
25            }
26         }
27     }
28 ////隐藏控制台
29 
30 using System.Runtime.InteropServices;//这个是必须的命名空间。
31 
32 
33 class ShadeConsole
34     {
35         [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
36         static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
37         [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
38         public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
39         public void shade()
40         {
41             Console.Title = "consoleWin";
42             IntPtr cwInptr = FindWindow("ConsoleWindowClass", "consoleWin");
43             if (cwInptr != IntPtr.Zero)
44             {
45                 ShowWindow(cwInptr, 0);
46             }
47         }
48     }
49 
50 ///多线程的实现,关闭到messagebox或者其他的窗体;
51 
52 using System.Threading;//多线程必要的。
53 
54 public static class MultiThread
55     {
56         public static void dowork()
57         {   
58            
59             ThreadPool.QueueUserWorkItem(new WaitCallback(s => {
60                 while (true)
61                 {
62                     SearchWindow sss = new SearchWindow();
63                     // Thread.Sleep(200);
64                     s = null;
65                     sss.closeWindow("DidiSoft.Pgp.PGPLib", "DidiSoft OpenPGP Library for .NET"); 
66                 }
67             }));
68         }
69 }
View Code

/////用法简介:

1》调用 MultiThread. Dowork();

2》       这弹出框前调用     Messagebox.show(“message”,”title”));

3》      因为弹出框会阻塞主线程。所以其他的线程调用要在主线程之前启动,让他一直垂询主线程。去获得句柄。

Tip: 这是使用开源的的pgp加密文件,它有个时间验证,特别麻烦,所以就想了,一招来关闭弹出框。谢谢!

原文地址:https://www.cnblogs.com/fandong90/p/4959654.html