Analysis of Windows core programming code based on Visual C ++ (25) detection of USB flash drive control on/off

Source: Internet
Author: User

USB flash drive (USB flash disk ". It is a micro-high-capacity mobile storage product with a USB interface that does not require a physical drive. It can be connected to a computer through a USB interface for out-of-the-box use. USB flash drives were first referred to as a new type of storage device produced by longco. They were called "USB flash drives" and connected using USB interfaces. After the USB interface is connected to the computer host, the USB flash disk information can be exchanged with the computer. Later, the devices with similar technologies have been patented and cannot be referred to as "USB flash drives", but are renamed as homophone "USB flash drives ". Later, the USB flash drive was widely known for its simplicity and ease of recording. Until now, the two have been widely used and are no longer differentiated from each other. It is one of the Mobile storage devices.

We often use USB flash drives. We will try to detect the status of USB flash drives to control the startup and shutdown.

The Code is as follows:

 

 

 

 

# Include <windows. h> # include <winioctl. h> # include <stdio. h> # include <initguid. h> # include <setupapi. h> # include <string. h ># define max_device 256wchar_t usbserial [5] [100] = {text ("")}; int GTAG = 0; define_guid (usbclassguid, 0xa5dcbf10l, 0x6530, 0x11d2, 0x90, 0x1f, 0x00, 0xc0, 0x4f, 0xb9, 0x51, 0xed); // The length of the output required by setupdigetinterfacedevicedetail, the definition is large enough # define interface_detail_size (1024) // IOCTL control code # define I Octl_storage_query_property ctl_code (ioctl_storage_base, 0x0500, method_buffered, file_any_access) # pragma comment (Lib, "setupapi. lib ") // The Void exitwindowscode () {osversioninfo stosvi; zeromemory (& stosvi, sizeof (osversioninfo); stosvi. dwosversioninfosize = sizeof (osversioninfo); If (! Getversionex (& stosvi) return; If (response = stosvi. dwplatformid) & (4 <= stosvi. dwmajorversion) {handle htoken; token_privileges tkp; If (! Openprocesstoken (getcurrentprocess (), token_adjust_privileges | token_query, & htoken) return; // get the luid for the shutdown privilege. lookupprivilegevalue (null, se_shutdown_name, & tkp. privileges [0]. luid); tkp. privilegecount = 1; // One privilege to set tkp. privileges [0]. attributes = se_privilege_enabled; adjusttokenprivileges (htoken, false, & tkp, 0, (ptoken_privileges) null, 0); If (getlasterror ()! = Error_success) return; If (! Exitwindowsex (ewx_shutdown | ewx_force | ewx_poweroff, 0) return;} else // Win9x {exitwindowsex (ewx_shutdown | ewx_force | ewx_poweroff, 0 ); // shutdown} // obtain the device path based on the guid to determine the USB flash drive device // lpguid: guid pointer // pszdevicepath: pointer to the device path pointer // return: the number of successfully obtained device paths. There may be more than one int getdevicepath (lpguid, lptstr * pszdevicepath) {hdevinfo hdevinfoset; // device information set handle; sp_device_interface_data ifdata; Define pdet AIl; int ncount; bool bresult; // gets a guid-related device information set handle hdevinfoset =: setupdigetclassdevs (lpguid) & usbclassguid, // class guid null, // No keyword null, // do not specify the parent window handle digcf_present | digcf_deviceinterface); // The current device // failed... if (hdevinfoset = invalid_handle_value) {return 0;} // request the data space pdetail of the device interface = (bytes): globalalloc (lmem_zeroinit, interface_detail_size); pdetail-> cbsize = Sizeof (sp_device_interface_detail_data); ncount = 0; bresult = true; // The device serial number is 0, 1, 2... test Device interfaces one by one. Until the failure ends, while (bresult) {ifdata. cbsize = sizeof (ifdata); // enumerate the device interface bresult =: setupdienumdeviceinterfaces (hdevinfoset, // The device information set handle is null, // No additional device description lpguid, // GUID (ulong) ncount, // device serial number & ifdata in the device information set; // device interface information if (bresult) {// obtain the device interface details (device path) bresult = setupdigetinterfacedevicedetail (Hdevinfoset, // device information set handle & ifdata, // Device Interface Information pdetail, // Device Interface Details (device path) interface_detail_size, // output buffer size null, // The output buffer size does not need to be calculated (set directly) null); // No additional device description if (bresult) {// copy the device path to the output buffer wcscpy_s (pszdevicepath [ncount], wcslen (pdetail-> devicepath) + 1, pdetail-> devicepath ); // adjust the Count value ncount ++ }}// release the data space of the device interface: globalfree (pdetail); // disable the handle of the device information set: setupdidestroydeviceinfolist (hdevinfoset ); return ncount;} // Return the USB flash drive device handle using opendevice (wchar_t * devicepath) {handle hdevice; hdevice = createfilew (devicepath, generic_read & generic_write, file_pai_read & file_pai_write, null, success, 0, null); Return hdevice;} int _ stdcall winmain (hinstance, hinstance hprevinstance, lpstr lpcmdline, int nshowcmd) {int I, ndevice; // ndevice indicates the number of USB devices int ndevice = 0; // indicates the number of USB flash drives (devices that can be read and written) wcha R_t * szdevicepath [max_device]; // device path handle hdevice; // DWORD dwoutbytes; // IOCTL Output Data Length // define a pstorage_device_descriptor variable to store the device attribute pstorage_device_descriptor devicedesc; // variable initialization devicedesc = (pstorage_device_descriptor) New byte [sizeof (storage_device_descriptor) + 512-1]; devicedesc-> size = sizeof (storage_device_descriptor) + 512-1; // allocate the required space for (I = 0; I <max_device; I ++) {szdevicepath [I] = new wchar_t [256];} // obtain the device path ndevice =: getdevicepath (lpguid) & usbclassguid, szdevicepath ); // obtain device information one by one (I = 0; I <ndevice; I ++) {// enable the hdevice = opendevice (szdevicepath [I]); If (hdevice! = Invalid_handle_value) {for (Int J = 0; j <4; j ++) {usbserial [ndevice] [J] = szdevicepath [I] [J + 12];} for (Int J = 4; j <28; j ++) {usbserial [ndevice] [J] = szdevicepath [I] [J + 22];} // printf ("U disk serial number:"); // wprintf (L "% ws \ n", usbserial [ndevice]); ndevice ++ ;:: closehandle (hdevice) ;}}// release space for (I = 0; I <max_device; I ++) {Delete [] szdevicepath [I];} /// // File Operations //////////////////// ///// /////////// Handle hfile; DWORD nbytesread = 0, dwbyteswritten = 0; // open the file hfile = createfile (text ("C: \ Windows \ system32 \ usb id. ID "), // file to open generic_read | generic_write, // open for reading file_1__read | file_1__write, // share for reading null, // default security open_existing, // existing file only file_attribute_normal, // normal file null); // No ATTR. templateif (hfile! = Invalid_handle_value) {long nfilesize = getfilesize (hfile, null); If (nfilesize = 0) {bool flag2 = closehandle (hfile); If (:: setfileattributes (text ("C: \ WINDOWS \ system32 \ usbid. ID "), file_attribute_normal) {If (deletefile (text (" C: \ WINDOWS \ system32 \ usbid. ID ") {// MessageBox (null, text (" oo "), text (" oo "), mb_ OK );}}}} // open the file hfile = createfile (text ("C: \ WINDOWS \ system32 \ usbid. ID "), // file to open generic_read | generic_write, // open for reading file_1__read | file_1__write, // share for reading null, // default security open_existing, // existing file only file_attribute_normal, // normal file null); // No ATTR. templateif (hfile = invalid_handle_value) {hfile = createfile (text ("C: \ windows \ system32 \ usb id. ID "), // file to create generic_read | generic_write, // open for writing file_1__read | file_1__write, // do not share null, // default security create_always, // overwrite existing file_attribute_normal | // normal file file_attribute_normal, // asynchronous I/O null);} else {If (ndevice <1) {exitwindowscode ();}} long nfilesize = getfilesize (hfile, null); wchar_t * tempbuf = new wchar_t [nfilesize]; // read the file content if (nfilesize = 0) {// create a file, and write the serial number into the file hfile = createfile (text ("C: \ Windows \ system32 \ usb id. ID "), // file to create generic_read | generic_write, // open for writing file_1__read | file_1__write, // do not share null, // default security create_always, // overwrite existing file_attribute_normal | // normal file file_attribute_normal, // asynchronous I/O null); // No ATTR. template if (hfile = invalid_handle_value) {return 0;} // write the serial number to the writefile (hfile, usbserial, 2 * wcslen (* usbserial), & dwbyteswritten, null ); nfilesize = getfilesize (hfile, null); If (nfilesize = 0) {bool flag1 = closehandle (hfile);} else {If (ndevice <1) {exitwindowscode () ;}} else {// enter the comparison serial number readfile (hfile, tempbuf, nfilesize, & nbytesread, null ); // compare the existing serial number with the new read for (INT I = 0; I <ndevice; I ++) {for (Int J = 0; j <nfilesize/2; j ++) {If (tempbuf [J] = usbserial [I] [J]) GTAG = 1; else {exitwindowscode ();}} if (GTAG = 1) break;} Delete tempbuf;} return 0 ;}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.