1 #include <windows.h>
2 #include <Shlwapi.h>
3 #include <fstream.h>
4 #include <TlHelp32.h>
5 #include <Dbt.h>
6
7  #pragma comment(lib,"shlwapi.lib")
8
9 #define TIMER 1//计时器
10
11 //function
12 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);//窗口过程
13 //获取盘符
14 TCHAR FirstDriveFromMask (ULONG unitmask);
15
16 //global variable
17 TCHAR szExePath[MAX_PATH];//the virus's path
18 TCHAR U[2];//保存U盘的盘符
19 TCHAR szSysPath[MAX_PATH];//system path
20
21 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
22 PSTR szCmdLine, int iCmdShow)
23 {
24 static TCHAR szAppName[]=TEXT ("UUUUUU");
25 HWND hwnd;
26 MSG msg;
27 WNDCLASS wndclass;
28
29 wndclass.style =0;
30 wndclass.lpfnWndProc =WndProc;
31 wndclass.cbClsExtra =0;
32 wndclass.cbWndExtra =0;
33 wndclass.hInstance =hInstance;
34 wndclass.hIcon =0;
35 wndclass.hCursor =0;
36 wndclass.hbrBackground =0;
37 wndclass.lpszMenuName =NULL;
38 wndclass.lpszClassName =szAppName;
39 if (!RegisterClass (&wndclass))
40 {
41 MessageBox (NULL,TEXT("Program requires Windows NT!"),
42 szAppName, MB_ICONERROR);
43 return 0;
44 }
45 hwnd = CreateWindow (szAppName, NULL,
46 WS_DISABLED,
47 0, 0,
48 0, 0,
49 NULL, NULL, hInstance, NULL);
50 while (GetMessage(&msg, NULL, 0, 0))
51 {
52 TranslateMessage (&msg);
53 DispatchMessage (&msg);
54 }
55 return msg.wParam;
56 }
57 LRESULT OnDeviceChange(HWND hwnd,WPARAM wParam, LPARAM lParam)
58 {
59 PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;
60 switch(wParam)
61 {
62 case DBT_DEVICEARRIVAL: //插入
63 if (lpdb -> dbch_devicetype == DBT_DEVTYP_VOLUME)
64 {
65 PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
66 U[0]=FirstDriveFromMask(lpdbv ->dbcv_unitmask);//得到u盘盘符
67 MessageBox(0,U,"Notice!",MB_OK);
68
69 }
70 break;
71 case DBT_DEVICEREMOVECOMPLETE: //设备删除
72 break;
73 }
74 return LRESULT();
75 }
76
77 LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam,LPARAM
78 lParam)
79 {
80 switch(message)
81 {
82 case WM_CREATE: //处理一些要下面要用到的全局变量
83 U[1]=':';
84
85 SetTimer(hwnd,TIMER,5000,0);//启动计时器
86
87 return 0;
88 case WM_TIMER: //timer message
89
90 SendMessage(hwnd,WM_DEVICECHANGE,0,0);//检测有没有插入设备消息
91
92 return 0;
93 case WM_DEVICECHANGE:
94 OnDeviceChange(hwnd,wParam,lParam);
95 return 0;
96 case WM_DESTROY:
97 KillTimer(hwnd,TIMER);
98 PostQuitMessage(0);
99 return 0;
100 }
101 return DefWindowProc(hwnd, message, wParam, lParam);
102 }
103
104 TCHAR FirstDriveFromMask(ULONG unitmask)
105 {
106 char i;
107 for (i = 0; i < 26; ++i)
108 {
109 if (unitmask & 0x1)//看该驱动器的状态是否发生了变化
110 break;
111 unitmask = unitmask >> 1;
112 }
113 return (i + 'A');
114 }

 

原理很简单,设置一个定时器,不断去检测设备是否变化。一旦有设备变化就去处理。 代码非原创,来自互联网,如果有侵权请告之。

posted on 2010-11-05 10:55  傅红血  阅读(2405)  评论(0)    收藏  举报