实用小工具:电脑插入U盘后自动打开文件夹

来源:互联网 发布:hr绿宝瓶面霜 知乎 编辑:程序博客网 时间:2024/06/11 04:10

>>工具说明<<
>>代码<<
>>下载地址<<


工具说明:

我笔记本不知怎么的插入U盘后在资源管理器中看不到盘符,只能通过设备管理器打开,很是麻烦,所以就自己开发了小工具,U盘插入后,会自动打开U盘所在的文件夹,代码很简单,在这里分享一下。
工具是基于C#语言的WinForm程序,无界面,开机自启动。


代码:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Diagnostics;using System.Drawing;using System.IO;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;using Microsoft.Win32;namespace U盘自动打开{    public partial class U盘自动打开 : Form    {        //监控U盘        const int WM_DEVICECHANGE = 0x219;        const int DBT_DEVICEARRIVAL = 0x8000; //如果m.Msg的值为0x8000那么表示有U盘插入        const int DBT_DEVICEREMOVECOMPLETE = 0X8004;        string[] preC = null; //最初的盘符数组        public U盘自动打开()        {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e)        {            this.Location = new Point(-1000, -1000);            preC = System.Environment.GetLogicalDrives();            //设置开启自启动            string path = Application.ExecutablePath;            RegistryKey rk = Registry.CurrentUser;            RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");            rk2.SetValue("U盘自动打开", path);            rk2.Close();            rk.Close();        }        /// <summary>        /// 监视Windows消息        /// </summary>        protected override void WndProc(ref Message m)        {            if (m.Msg == WM_DEVICECHANGE)            {                switch (m.WParam.ToInt32())                {                    case DBT_DEVICEARRIVAL://U盘插入                        String[] curC = Environment.GetLogicalDrives();                        DriveInfo upanRootPath = null;                        foreach (string item in curC)                        {                            if (!preC.Contains(item))                            {                                upanRootPath = new DriveInfo(item);                                while (!upanRootPath.IsReady)                                {                                    Thread.Sleep(500);                                }                                break;                            }                        }                        if (upanRootPath == null)                            return;                        Process.Start("explorer.exe", upanRootPath.RootDirectory.FullName);                        break;                    case DBT_DEVICEREMOVECOMPLETE:   //U盘卸载                        string[] tmpC = System.Environment.GetLogicalDrives();                        if (tmpC.Length < preC.Length)                            preC = tmpC;                        break;                    default:                        break;                }            }            base.WndProc(ref m); //将系统消息传递自父类的WndProc        }    }}

下载地址:

http://download.csdn.net/detail/u010784236/9548424

0 0