C#系统操作汇总

来源:互联网 发布:c语言long是什么意思 编辑:程序博客网 时间:2024/05/17 08:37

 

 

▲资源包括c#对操作系统的各种操作方法▲ ▲设置桌面背景▲ ▲设置系统时间▲ ▲设置屏幕分辨率▲ ▲设置鼠标样式▲ ▲设置任务栏时间显示方式▲ ▲进入系统前弹出信息▲ ▲内存使用状态 ▲CPU使用率▲ ▲键盘钩子屏保热键▲ ▲获取系统启动后经过的时间▲ ▲检索系统中正在运行的任务▲ 隐藏显示任务栏▲ 隐藏显示开始按钮▲ 隐藏显示桌面图标▲ 使桌面图标文字透明▲ 设置输入法▲ 获取鼠标在任意点的颜色值▲ 限制鼠标的活动区域▲ 获取磁盘序列号▲ 设置映射驱动器路径▲ 判断驱动器类型▲ 获取所有逻辑驱动器▲ 取消磁盘共享▲ 驱动器容量▲ 图标显示磁盘容量▲ 磁盘格式化▲ 打开控制面板的程序▲ 添加磁盘到托盘▲ 任务栏上不出现图标▲ 调用外部EXE文件▲ 关闭外部程序▲ 防止程序多次运行▲ 获取任务栏尺寸▲ 程序运行时禁止关机▲ 改变系统提示信息▲ 获取环境变量▲ 启动屏幕保护▲

 系统设置

磁盘管理程序控制

 

 本文源码下载 

一.系统设置                                                                          

1.1设置桌面背景                                                                      设置桌面背景的关键技术是通过API函数 SystemParametersInfo将指定的图片设置为电脑背景桌面,该函数允许获取或设置windows系统参数。       语法格式如下:
[DllImport("user32.dll", EntryPoint = "SystemParametersInfoA")] static extern Int32 SystemParametersInfo(Int32 uAction, Int32 uParam, string lpvparam, Int32 fuwinIni);
关键代码
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, 1); //设置桌面背景 ( SPI_SETDESKWALLPAPER=20     path 图片路径)

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;using System.IO;using System.Drawing.Imaging;namespace SystemSettings{    public partial class DeskTop101 : Form    {        [DllImport("user32.dll", EntryPoint = "SystemParametersInfoA")]        static extern Int32 SystemParametersInfo(Int32 uAction, Int32 uParam, string lpvparam, Int32 fuwinIni);        public string picturepath = "";        private const int SPI_SETDESKWALLPAPER = 20;        public Image image;        public DeskTop101()        {            InitializeComponent();        }        private void button_openfile_Click(object sender, EventArgs e)        {            label_show.Visible = false;            pictureBox_show.Visible = true;            OpenFileDialog ofd = new OpenFileDialog();            ofd.Filter = "*.jpg;*.jpeg;*.gif;*.png;*.bmp|*.jpeg;*.jpg;*.gif;*.png;*.bmp";            if (ofd.ShowDialog() == DialogResult.OK)            {                picturepath = ofd.FileName;                image = System.Drawing.Image.FromFile(picturepath);                pictureBox_show.Image = image;            }        }        private void button_setDesktop_Click(object sender, EventArgs e)        {            string SFileType = "";            string filename = "";            if (picturepath == "")            {                MessageBox.Show("请选择图片");            }            else            {                //获取文件后缀                SFileType = picturepath.Substring(picturepath.LastIndexOf(".") + 1, (picturepath.Length - picturepath.LastIndexOf(".") - 1));                SFileType = SFileType.ToLower();                //获取文件名                filename = picturepath.Substring(picturepath.LastIndexOf("\\") + 1, (picturepath.LastIndexOf(".") - picturepath.LastIndexOf("\\") - 1));                if (SFileType == "bmp")                {                    SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, picturepath, 1); //设置背景                }                else                {                    string SystemPath = Environment.SystemDirectory;//获取系统文件路径                    string path = SystemPath + "\\" + filename + ".bmp";                    FileInfo fi = new FileInfo(path);                    if (fi.Exists)                    {                        fi.Delete();                        PictureBox pb = new PictureBox();                        pb.Image = Image.FromFile(picturepath);                        pb.Image.Save(SystemPath + "\\" + filename + ".bmp", ImageFormat.Bmp);//实现格式转换                    }                    else                    {                        PictureBox pb = new PictureBox();                        pb.Image = Image.FromFile(picturepath);                        pb.Image.Save(SystemPath + "\\" + filename + ".bmp", ImageFormat.Bmp);//实现格式转换                    }                    SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, 1); //设置背景                }            }        }        private void DeskTop101_Load(object sender, EventArgs e)        {            pictureBox_show.Visible = false;        }        private void button_change_Click(object sender, EventArgs e)        {            pictureBox_show.Visible = false;            label_show.Visible = true;        }    }}




 

1.2 设置系统时间                                   

c# 中修改系统时间可以使用API函数SetSystemTime 和SetLocalTime 来修改系统时间。
本例用SetLocalTime修改系统时间
过程是:
1.创建一个SYSTEMTIME的struct结构  在结构中包括 年,月,一周的第几天,日,小时,分,秒,毫秒
2.调用SetLocalTime即可修改系统时间
关键代码
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SYSTEMTIME Time);
[DllImport("Kernel32.dll")]
public static extern void GetLocalTime(ref SYSTEMTIME Time);
...bool v = SetLocalTime(ref t); //调用SetLocalTime函数使设置的时间生效
其中创建一个SystemEvents_TimeChanged(object sender, EventArgs e)来提示时间本修改
在初始化是添加Microsoft.Win32.SystemEvents.TimeChanged+=new EventHandler(SystemEvents_TimeChanged);

 

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;using ".Win32;namespace SystemSettings{    public partial class SystemTime102 : Form    {        [DllImport("Kernel32.dll")]        public static extern bool SetLocalTime(ref SYSTEMTIME Time);        [DllImport("Kernel32.dll")]        public static extern void GetLocalTime(ref SYSTEMTIME Time);        [StructLayout(LayoutKind.Sequential)]        public struct SYSTEMTIME        {            public short Year;            public short Month;            public short DayOfWeek;            public short Day;            public short Hour;            public short Mintute;            public short Second;            public short Miliseconds;        }        public SystemTime102()        {            InitializeComponent();        }        private void button_Setting_Click(object sender, EventArgs e)        {            SYSTEMTIME t = new SYSTEMTIME();            t.Year = (short)(dateTimePicker_date.Value.Year);            t.Month = (short)(dateTimePicker_date.Value.Month);            t.Day = (short)(dateTimePicker_date.Value.Day);            t.Hour = (short)(dateTimePicker_SystemTime.Value.Hour);            t.Mintute = (short)(dateTimePicker_SystemTime.Value.Minute);            t.Second = (short)(dateTimePicker_SystemTime.Value.Second);            bool v = SetLocalTime(ref t);        }        private void SystemTime102_Load(object sender, EventArgs e)        {            ".Win32.SystemEvents.TimeChanged+=new EventHandler(SystemEvents_TimeChanged);        }        private void dateTimePicker_SystemTime_ValueChanged(object sender, EventArgs e)        {        }        private void SystemEvents_TimeChanged(object sender, EventArgs e)        {            MessageBox.Show("系统时间被改变了,现在时间为:" + DateTime.Now.ToString());        }    }}


 

1.3 设置屏幕分辨率

切换屏幕分辨率的API函数ChangeDisplaySettings
该函数把缺省显示设备的设置改变为由lpDevMode设定的图形模式
其中关键要加入
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DEVMODE{..... }
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int ChangeDisplaySettings([In] ref DEVMODE lpDevMode, int dwFlags);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern bool EnumDisplaySettings(string lpszDeviceName, Int32 iModeNum, ref DEVMODE lpDevMode);
//修改分辨率的方法是
先定义一个DEVMODE DevM = new DEVMODE();
在调用 long result = ChangeDisplaySettings(ref DevM, 0);

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;using Microsoft.Win32;namespace SystemSettings{    public partial class ScreenResolution103 : Form    {        //获取并保存当前屏幕分辨率          public int current_width = Screen.PrimaryScreen.Bounds.Width;        public int current_height = Screen.PrimaryScreen.Bounds.Height;        public int S_Width = 800;        public int S_Hight = 600;        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]        public struct DEVMODE        {            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]            public string dmDeviceName;            public short dmSpecVersion;            public short dmDriverVersion;            public short dmSize;            public short dmDriverExtra;            public int dmFields;            public short dmOrientation;            public short dmPaperSize;            public short dmPaperLength;            public short dmPaperWidth;            public short dmScale;            public short dmCopies;            public short dmDefaultSource;            public short dmPrintQuality;            public short dmColor;            public short dmDuplex;            public short dmYResolution;            public short dmTTOption;            public short dmCollate;            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]            public string dmFormName;            public short dmLogPixels;            public int dmBitsPerPel;            public int dmPelsWidth;            public int dmPelsHeight;            public int dmDisplayFlags;            public int dmDisplayFrequency;        }        [DllImport("user32.dll", CharSet = CharSet.Auto)]        static extern int ChangeDisplaySettings([In] ref DEVMODE lpDevMode, int dwFlags);        [DllImport("user32.dll", CharSet = CharSet.Auto)]        static extern bool EnumDisplaySettings(string lpszDeviceName, Int32 iModeNum, ref DEVMODE lpDevMode);        /// <summary>        /// 改变分辨率        /// </summary>        public void ChangeRes(int w, int h)        {            DEVMODE DevM = new DEVMODE();            DevM.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE));            bool mybool;            mybool = EnumDisplaySettings(null, 0, ref DevM);            DevM.dmPelsWidth = w;      //设置宽            DevM.dmPelsHeight = h;       //设置高            DevM.dmDisplayFrequency = 60;      //刷新频率            DevM.dmBitsPerPel = 32;          //颜色象素            long result = ChangeDisplaySettings(ref DevM, 0);        }        /// <summary>        /// 复原屏幕分辨率        /// </summary>        void FuYuan()        {            DEVMODE DevM = new DEVMODE();            DevM.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE));            bool mybool;            mybool = EnumDisplaySettings(null, 0, ref DevM);            DevM.dmPelsWidth = current_width;      //恢复宽            DevM.dmPelsHeight = current_height;     //恢复高            DevM.dmDisplayFrequency = 60;         //刷新频率            DevM.dmBitsPerPel = 32;               //颜色象素            long result = ChangeDisplaySettings(ref DevM, 0);        }        public ScreenResolution103()        {            InitializeComponent();        }        private void button_setting_Click(object sender, EventArgs e)        {            ChangeRes(S_Width, S_Hight);        }        private void button_fuyuan_Click(object sender, EventArgs e)        {            FuYuan();        }        private void trackBar_showscreen_Scroll(object sender, EventArgs e)        {            switch (trackBar_showscreen.Value)            {                case 1:                    S_Width = 800;                    S_Hight = 600;                    break;                case 2:                    S_Width = 1024;                    S_Hight = 768;                    break;                case 3:                    S_Width = 1152;                    S_Hight = 864;                    break;                case 4:                    S_Width = 1280;                    S_Hight = 600;                    break;                case 5:                    S_Width = 1280;                    S_Hight = 720;                    break;                case 6:                    S_Width = 1280;                    S_Hight = 960;                    break;                case 7:                    S_Width = 1280;                    S_Hight = 1024;                    break;                case 8:                    S_Width = 1400;                    S_Hight = 1050;                    break;                case 9:                    S_Width = 1440;                    S_Hight = 900;                    break;                case 10:                    S_Width = 1600;                    S_Hight = 900;                    break;                case 11:                    S_Width = 1600;                    S_Hight = 1200;                    break;                case 13:                    S_Width = 1580;                    S_Hight = 1050;                    break;                default:                    S_Hight = current_height;                    S_Width = current_width;                    break;            }            label_show.Text = S_Width + " X " + S_Hight;        }    }}


1.4设置鼠标样式

设置鼠标样式通调用API 下的LoadCursorFromFile和SetSystemCursor实现
[DllImport("user32.dll",EntryPoint="LoadCursorFromFile")]
public static extern int IntLoadCursorFromFile(string fileName);
[DllImport("user32.dll",EntryPoint="SetSystemCursor")]
public static extern void SetSystemCursor(int hcur,int i);
恢复系统图标样式采用
[DllImport("User32.DLL")]
public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni);
其中将cur文件加入dll的方法是:
1.双击Resource.resx(如果资源管理器中没有这一项只需右击项目选择添加——>新建项——>资源文件即可)添加要显示的光标文件。添加完成后,资源管理器中会出现Resources文件夹,我们添加的项目就会出现在这里,如user.cur。
2.更改光标
2.1 添加引用  using System.Runtime.InteropServices;
2.2 在程序中声明光标资源加载函数LoadCursorFromFile;
[DllImport("user32")]
private static extern IntPtr LoadCursorFromFile(string fileName);
2.3 声明数组 byte[] cursorbuffer=namespace.Resource .CursorName;
Namespace为资源文件所在项目的命名空间名称,CursorName对应光标资源文件名。
2.4 创建一个临时光标文件tempTest.dat;将cursorbuffer中的数据写入数据文件中;
FileStream fileStream = new FileStream("tempTest.dat", FileMode. Create);
fileStream.Write(cursorbuffer, 0, cursorbuffer.Length);
2.5  关闭文件,利用API 函数LoadCursorFromFile从光标临时文件中创建光标。
fileStream.Close();
Cursor .Current =new Cursor(LoadCursorFromFile("temp001.dat"));

 

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using SystemSettings.Properties;using System.IO;using System.Runtime.InteropServices;namespace SystemSettings{    public partial class MouseStyle104 : Form    {        [DllImport("user32.dll", EntryPoint = "LoadCursorFromFile")]        public static extern int IntLoadCursorFromFile(string fileName);        [DllImport("user32.dll", EntryPoint = "SetSystemCursor")]        public static extern void SetSystemCursor(int hcur, int i);        public const int OCR_NORAAC = 32512;        public const int OCR_HAND = 32649;        public const int OCR_NO = 32648;        public const int OCR_SIZEALL = 32646;        [DllImport("User32.DLL")]        public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni);        public MouseStyle104()        {            InitializeComponent();        }        public string WindowsPath = "";        public string CursorsPath = "";        private void MouseStyle104_Load(object sender, EventArgs e)        {            WindowsPath = Environment.GetEnvironmentVariable("WinDir");            CursorsPath = WindowsPath + "\\Cursors";        }        private void comboBox_mouseStyle_DrawItem(object sender, DrawItemEventArgs e)        {            Graphics GComboBox = e.Graphics;   //声明一个GDI的绘图类对象            Rectangle RComboBox = e.Bounds;    //表示矩形的位置和大小的对象        }        private void comboBox_mouseStyle_SelectedIndexChanged(object sender, EventArgs e)        {            DirectoryInfo di = new DirectoryInfo(CursorsPath + @"\Image");            if (!di.Exists)            {                di.Create();            }            byte[] cursorbuffer = null;            switch (comboBox_mouseStyle.SelectedIndex)            {                case 0:                    break;                case 1:                    cursorbuffer = Resources.mouse001;                    break;                case 2:                    cursorbuffer = Resources.mouse002;                    break;                case 3:                    cursorbuffer = Resources.mouse003;                    break;                case 4:                    cursorbuffer = Resources.mouse005;                    break;                default:                    cursorbuffer = Resources.mouse001;                    break;            }            if (comboBox_mouseStyle.SelectedIndex != 0)            {                FileStream fileStream = new FileStream("tempTest.cur", FileMode.Create);                fileStream.Write(cursorbuffer, 0, cursorbuffer.Length);                fileStream.Close();                File.Copy("tempTest.cur", CursorsPath + @"\Image\" + "tempTest.cur", true);                int cur = IntLoadCursorFromFile(CursorsPath + @"\Image\tempTest.cur");                SetSystemCursor(cur, OCR_NORAAC);            }            else            {                SystemParametersInfo(87, 0, IntPtr.Zero, 2);                // SetSystemCursor(Cursors.Arrow.CopyHandle().ToInt32(), OCR_NORAAC);            }        }    }}


1.5设置任务栏时间显示方式

修改时间样式主要通过修改注册表的方法来实现
注册表的地址HKEY_CURRENT_USER\Control Panel\International 添加一个sTimeFormat 为 H:mm:ss  HH:mm:ss tt h:mm:ss tt hh:mm:ss
关键代码
RegistryKey mreg;
mreg = Registry.CurrentUser;
mreg = mreg.CreateSubKey(@"control Panel\International");
mreg.SetValue("sTimeFormat", comboBox_timeStyle.Text.Trim());

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using Microsoft.Win32;using System.Runtime.InteropServices;using System.Diagnostics;namespace SystemSettings{    public partial class TimeStyle105 : Form    {        const uint ULNTERVAL = 400;        [DllImport("user32")]        public static extern bool SetDoubleClickTime(uint ulnterval);        const int WM_SETTINGCHANGE = 0x001A;        const int HWND_BROADCAST = 0xffff;        #region public enum HChangeNotifyFlags        [Flags]        public enum HChangeNotifyFlags        {            SHCNF_DWORD = 0x0003,            SHCNF_IDLIST = 0x0000,            SHCNF_PATHA = 0x0001,            SHCNF_PATHW = 0x0005,            SHCNF_PRINTERA = 0x0002,            SHCNF_PRINTERW = 0x0006,            SHCNF_FLUSH = 0x1000,            SHCNF_FLUSHNOWAIT = 0x2000        }        #endregion // enum HChangeNotifyFlags        #region enum HChangeNotifyEventID        [Flags]        enum HChangeNotifyEventID        {            SHCNE_ALLEVENTS = 0x7FFFFFFF,            SHCNE_ASSOCCHANGED = 0x08000000,            SHCNE_ATTRIBUTES = 0x00000800,            SHCNE_CREATE = 0x00000002,            SHCNE_DELETE = 0x00000004,            SHCNE_DRIVEADD = 0x00000100,            SHCNE_DRIVEADDGUI = 0x00010000,            SHCNE_DRIVEREMOVED = 0x00000080,            SHCNE_EXTENDED_EVENT = 0x04000000,            SHCNE_FREESPACE = 0x00040000,            SHCNE_MEDIAINSERTED = 0x00000020,            SHCNE_MEDIAREMOVED = 0x00000040,            SHCNE_MKDIR = 0x00000008,            SHCNE_NETSHARE = 0x00000200,            SHCNE_NETUNSHARE = 0x00000400,            SHCNE_RENAMEFOLDER = 0x00020000,            SHCNE_RENAMEITEM = 0x00000001,            SHCNE_RMDIR = 0x00000010,            SHCNE_SERVERDISCONNECT = 0x00004000,            SHCNE_UPDATEDIR = 0x00001000,            SHCNE_UPDATEIMAGE = 0x00008000,        }        [DllImport("shell32.dll")]        static extern void SHChangeNotify(HChangeNotifyEventID wEventId,                                           HChangeNotifyFlags uFlags,                                           IntPtr dwItem1,                                           IntPtr dwItem2);        #endregion // enum HChangeNotifyEventID        IntPtr result1;        public enum SendMessageTimeoutFlags : uint        {            SMTO_NORMAL = 0x0000,            SMTO_BLOCK = 0x0001,            SMTO_ABORTIFHUNG = 0x0002,            SMTO_NOTIMEOUTIFNOTHUNG = 0x0008        }        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]        public static extern IntPtr SendMessageTimeout(        IntPtr windowHandle,        uint Msg,        IntPtr wParam,        IntPtr lParam,        SendMessageTimeoutFlags flags,        uint timeout,        out IntPtr result        );        public void ChangeReg()        {            //通知所有打开的程序注册表以修改             SendMessageTimeout(new IntPtr(HWND_BROADCAST), WM_SETTINGCHANGE, IntPtr.Zero, IntPtr.Zero, SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out result1);        }        public TimeStyle105()        {            InitializeComponent();        }        private void button_setting_Click(object sender, EventArgs e)        {            if (comboBox_timeStyle.Text != "")    //如果选择了时间样式            {                RegistryKey mreg;                mreg = Registry.CurrentUser;                mreg = mreg.CreateSubKey(@"control Panel\International");                mreg.SetValue("sTimeFormat", comboBox_timeStyle.Text.Trim());                mreg.Close();                ChangeReg();                SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);                if (MessageBox.Show("修改成功,重启有效,是否需求强制刷新(有时候会使打开的文件夹消失)", "修改成功", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)                {                    RefreshSystem();                }                SetDoubleClickTime(ULNTERVAL);            }        }        public void RefreshSystem()        {            Process[] myProcesses;            myProcesses = Process.GetProcessesByName("explorer");            foreach (Process myProcess in myProcesses)            {                myProcess.Kill();            }            System.Diagnostics.Process.Start("explorer.exe");        }    }}


1.6进入系统前弹出信息

修改时间样式主要通过修改注册表的方法来实现
注册表的地址HKEY_CURRENT_USER\Control Panel\International 添加一个sTimeFormat 为 H:mm:ss  HH:mm:ss tt h:mm:ss tt hh:mm:ss
关键代码
RegistryKey mreg;
mreg = Registry.CurrentUser;
mreg = mreg.CreateSubKey(@"control Panel\International");
mreg.SetValue("sTimeFormat", comboBox_timeStyle.Text.Trim());
删除提示 用DeleteValue 不能用DeleteSubKey 注意区别
手动方法为:找到HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Winlogon
这一个主键,然后在右边窗口中找到“LegalNoticeCaption”和“LegalNoticeText”这两个字符串,删除这两个字符串就可以解决在登陆时出现提示框的现象了。

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using Microsoft.Win32;namespace SystemSettings{    public partial class OSInformation106 : Form    {        public OSInformation106()        {            InitializeComponent();        }        private void button_setting_Click(object sender, EventArgs e)        {            if (textBox_nr.Text == "" || textBox_title.Text == "")            {                MessageBox.Show("请输入标题和内容");            }            else            {                RegistryKey rKey = Registry.LocalMachine;                RegistryKey rKeyInfo = rKey.CreateSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon");                rKeyInfo.SetValue("LegalNoticeCaption", textBox_title.Text, RegistryValueKind.String);                rKeyInfo.SetValue("LegalNoticeText", textBox_nr.Text, RegistryValueKind.String);                MessageBox.Show("已经完成设置,重启生效", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);            }        }        private void button_cancel_Click(object sender, EventArgs e)        {            DeleteRegist("LegalNoticeCaption");            DeleteRegist("LegalNoticeText");            MessageBox.Show("删除成功");        }        public void DeleteRegist(string name)        {            RegistryKey hkml = Registry.LocalMachine;            RegistryKey software = hkml.OpenSubKey("SOFTWARE", true);            RegistryKey software1 = software.OpenSubKey("Microsoft", true);            RegistryKey software2 = software1.OpenSubKey("Windows NT", true);            RegistryKey software3 = software2.OpenSubKey("CurrentVersion", true);            RegistryKey aimdir = software3.OpenSubKey("Winlogon", true);            aimdir.DeleteValue(name.Trim(), false);            aimdir.Close();            software3.Close();            software2.Close();            software1.Close();            hkml.Close();        }    }}


二.系统监控

2.1内存使用状态

查看系统内存在本示例中采用了.NET Framework 2.0 版中是新增的命名空间:Microsoft.VisualBasic.Devices
程序集:Microsoft.VisualBasic(在 microsoft.visualbasic.dll 中)
关键代码
Computer myComputer = new Computer();
textBox_TPM.Text = Convert.ToString(myComputer.Info.TotalPhysicalMemory / 1024 / 1024)+"M";
textBox_TVM.Text = Convert.ToString(myComputer.Info.TotalVirtualMemory / 1024 / 1024)+"M";
textBox_APM.Text = Convert.ToString(myComputer.Info.AvailablePhysicalMemory / 1024 / 1024)+"M";
textBox_AVM.Text = Convert.ToString(myComputer.Info.AvailableVirtualMemory / 1024 / 1024)+"M";

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using Microsoft.VisualBasic.Devices;namespace SystemSettings{    public partial class MemoryUsage201 : Form    {        public MemoryUsage201()        {            InitializeComponent();        }        private void MemoryUsage201_Load(object sender, EventArgs e)        {            this.timer1.Start();        }        private void timer1_Tick(object sender, EventArgs e)        {            Computer myComputer = new Computer();            textBox_TPM.Text = Convert.ToString(myComputer.Info.TotalPhysicalMemory / 1024 / 1024) + "M";            textBox_TVM.Text = Convert.ToString(myComputer.Info.TotalVirtualMemory / 1024 / 1024) + "M";            textBox_APM.Text = Convert.ToString(myComputer.Info.AvailablePhysicalMemory / 1024 / 1024) + "M";            textBox_AVM.Text = Convert.ToString(myComputer.Info.AvailableVirtualMemory / 1024 / 1024) + "M";        }    }}


2.2CPU使用率

CPU使用率采用的方法是调用ManagementObjectSearcher类的LoadPercentage属性可以快速的获取CPU使用率
ManagementObjectSearcher所引用的空间是using System.Management; 要添加系统提供的dll
ManagementObjectSearcher seracher = new ManagementObjectSearcher("select * from Win32_Processor");
foreach (ManagementObject myobject in seracher.Get())
{   label_text.Text = myobject["LoadPercentage"].ToString() + "%";   }
采用的是WMI查询 可以查看系统的许多信息

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Management;using System.Threading;namespace SystemSettings{    public partial class CUP202 : Form    {        public CUP202()        {            InitializeComponent();        }        private void CUP202_Load(object sender, EventArgs e)        {            timer1.Start();        }        /// <summary>        /// 获取内存信息        /// </summary>        public void MyUser()        {            ManagementObjectSearcher seracher = new ManagementObjectSearcher("select * from Win32_Processor");            foreach (ManagementObject myobject in seracher.Get())            {                label_text.Text = myobject["LoadPercentage"].ToString() + "%";            }            //CreateImage();        }        private void timer1_Tick(object sender, EventArgs e)        {            Thread t = new Thread(MyUser);            t.Start();        }    }}


2.3键盘钩子屏蔽热键

HooK钩子是windows消息处理机制的一个平台,应用程序可以在上面设置子进程以监视指定窗口的某种消息,
可以监视程序的运行,可以屏蔽一些热键 ALT+F4 Win+D 等等,也可以监视屏蔽软件的热键等等.
1.安装钩子
  [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]//安装钩子
public static extern IntPtr SetWindowsHookEx(int idHook,HookProc ipfn,IntPtr pInstance, int threadId);
2.卸载钩子
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]   //卸载钩子
public static extern bool UnhookWindowsHookEx(IntPtr pHookHandle);
关键代码

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;using System.Reflection;namespace SystemSettings{    public partial class Hook203 : Form    {        [StructLayout(LayoutKind.Sequential)]        public struct KeyMSG        {            public int vkCode;            public int scanCode;            public int flags;            public int time;            public int dwExtraInfo;        }        private IntPtr pKeyboardHook = IntPtr.Zero;                            //键盘钩子句柄        public delegate int HookProc(int nCode, Int32 wParam, IntPtr IParam);   //钩子委托声明        private HookProc KeyboardHookProcedure;                                //键盘钩子委托实例不能省略的变量               public const int idHook = 13;                                          //底层键盘钩子        [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]//安装钩子        public static extern IntPtr SetWindowsHookEx(int idHook, HookProc ipfn, IntPtr pInstance, int threadId);        [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]   //卸载钩子        public static extern bool UnhookWindowsHookEx(IntPtr pHookHandle);        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr IParam)     //键盘钩子处理函数        {            KeyMSG m = (KeyMSG)Marshal.PtrToStructure(IParam, typeof(KeyMSG));            if (pKeyboardHook != IntPtr.Zero)            {                switch (((Keys)m.vkCode))                {                    case Keys.LWin:                    case Keys.RWin:                    case Keys.Delete:                    case Keys.Alt:                    case Keys.Escape:                    case Keys.F4:                    case Keys.Control:                    case Keys.Tab:                    case Keys.Z:                    case Keys.ControlKey:                        return 1;                }            }            return 0;        }        /// <summary>        /// 安装钩子        /// </summary>        /// <returns></returns>        public bool InsertHook()        {            IntPtr pIn = (IntPtr)4194304;            if (this.pKeyboardHook == IntPtr.Zero)            {                this.KeyboardHookProcedure = new HookProc(KeyboardHookProc);                this.pKeyboardHook = SetWindowsHookEx(idHook, KeyboardHookProcedure, pIn, 0);                if (this.pKeyboardHook == IntPtr.Zero)                {                    this.UnInsertHook();                    return false;                }            }            return true;     //安装成功        }        public bool UnInsertHook()        {            bool result = true;            if (this.pKeyboardHook != IntPtr.Zero)            {                result = (UnhookWindowsHookEx(this.pKeyboardHook) && result);   //卸载钩子                this.pKeyboardHook = IntPtr.Zero;            }            return result;        }        public Hook203()        {            InitializeComponent();        }        private void button_hack_Click(object sender, EventArgs e)        {            InsertHook();        }        private void button_unhack_Click(object sender, EventArgs e)        {            UnInsertHook();        }    }}


2.4获取系统启动后进过的时间

通过Environment使用TickCount属性可快速获取系统启动后经过的时间

int totals=Environment.TickCount/1000;

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace SystemSettings{    public partial class systemstarts204 : Form    {        public systemstarts204()        {            InitializeComponent();        }        public void getTime()        {            int totals = Environment.TickCount / 1000;            label_title.Text = "系统启动后经过的时间:" + (totals / 3600) + "小时" + (totals - (totals / 3600) * 3600) / 60 + "分" + (totals - (totals / 3600) * 3600 - ((totals - (totals / 3600) * 3600) / 60) * 60) + "秒";        }        private void systemstarts204_Load(object sender, EventArgs e)        {            this.timer1.Start();        }        private void timer1_Tick(object sender, EventArgs e)        {            getTime();        }    }}


2.5检索系统正在运行的任务

主要是使用了Process类中的GetProcesses方法为系统中正在运行的任务创建一个Process对象
所有代码:
richTextBox_task.Text = string.Empty;
            Process[] myProcesses = Process.GetProcesses();
            foreach (Process myProcess in myProcesses)
            {
                if (myProcess.MainWindowTitle.Length > 0)
                {
                    richTextBox_task.Text += "----------------------"+"\n";
                    richTextBox_task.Text += "任务名:" + myProcess.MainWindowTitle + "\n";
                    richTextBox_task.Text += "当前窗口主进程的句柄" + myProcess.MainWindowHandle + "\n";
                }
            }

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Diagnostics;namespace SystemSettings{    public partial class RunningTask205 : Form    {        public RunningTask205()        {            InitializeComponent();        }        private void timer1_Tick(object sender, EventArgs e)        {            richTextBox_task.Text = string.Empty;            Process[] myProcesses = Process.GetProcesses();            foreach (Process myProcess in myProcesses)            {                if (myProcess.MainWindowTitle.Length > 0)                {                    richTextBox_task.Text += "----------------------" + "\n";                    richTextBox_task.Text += "任务名:" + myProcess.MainWindowTitle + "\n";                    richTextBox_task.Text += "当前窗口主进程的句柄" + myProcess.MainWindowHandle + "\n";                }            }        }        private void RunningTask205_Load(object sender, EventArgs e)        {            timer1.Start();        }    }}


三.系统隐藏

3.1 隐藏显示任务栏

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace SystemSettings{    public partial class HideTaskbar301 : Form    {        private int SW_HIDE = 0;        private int SW_RESTORE = 9;        [DllImport("user32.dll")]        public static extern int FindWindow(string lpClassName, string lpWindowName);        [DllImport("user32.dll")]        public static extern int ShowWindow(int hwnd, int nCmdShow);        public HideTaskbar301()        {            InitializeComponent();        }        private void button_show_Click(object sender, EventArgs e)        {            ShowWindow(FindWindow("Shell_TrayWnd", null), SW_RESTORE);        }        private void button_hide_Click(object sender, EventArgs e)        {            ShowWindow(FindWindow("Shell_TrayWnd", null), SW_HIDE);        }    }}


3.2隐藏显示开始按钮

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace SystemSettings{    public partial class HideStart302 : Form    {        public const int SW_HIDE = 0;        public const int SW_SHOW = 5;        [DllImport("user32.dll")]       //寻找窗口列表中第一个符合指定条件的顶级窗口        public static extern int FindWindow(string lpClassName, string lpWindowName);        [DllImport("user32.dll")]      //寻找窗口列表中指定与寻找条件相符的第1个子窗口        public static extern int FindWindowEx(int hWnd1, int hWnd2, string lpsz1, string lpsz2);        [DllImport("user32.dll")]      //控制窗口的可见性        public static extern int ShowWindow(int hwnd, int nCmdShow);        public HideStart302()        {            InitializeComponent();        }        private void button_hide_Click(object sender, EventArgs e)        {            ShowWindow(FindWindowEx(FindWindow("Shell_TrayWnd", null), 0, "Button", null), SW_HIDE);        }        private void button_show_Click(object sender, EventArgs e)        {            ShowWindow(FindWindowEx(FindWindow("Shell_TrayWnd", null), 0, "Button", null), SW_SHOW);        }        private void HideStart302_Load(object sender, EventArgs e)        {        }    }}


3.3隐藏显示桌面图标

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace SystemSettings{    public partial class HidedesktopIcos303 : Form    {        [DllImport("user32.dll")]        public static extern bool ShowWindow(int hWnd, short nCmdShow);        [DllImport("user32.dll")]        public static extern int FindWindow(string lpClassName, string lpWindowName);        private const int GW_CHILD = 5;        private const int SW_HIDE = 0;        private const int SW_SHOWNORMAL = 1;        public HidedesktopIcos303()        {            InitializeComponent();        }        private void button_hide_Click(object sender, EventArgs e)        {            int hWnd1;            hWnd1 = FindWindow("Progman", null);            ShowWindow(hWnd1, SW_HIDE);        }        private void button_show_Click(object sender, EventArgs e)        {            int hWnd1;            hWnd1 = FindWindow("Progman", null);            ShowWindow(hWnd1, SW_SHOWNORMAL);        }        private void HidedesktopIcos303_Load(object sender, EventArgs e)        {        }    }}


3.4使桌面图标透明

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace SystemSettings{    public partial class DeskTopIco304 : Form    {        [DllImport("user32.dll")]        public static extern int GetDesktopWindow(); //获得一个代表整个窗体(桌面)的句柄        [DllImport("user32.dll")]        public static extern int FindWindowEx(int Hwnd1, int Hwnd2, string lpsz1, string lpsz2);//在窗口列表中寻找与指定条件相符的第一个子窗口        [DllImport("user32.dll")]        public static extern int SendMessage(int hwnd, int wMg, int wParam, uint lParam);//调用一个窗口函数,将消息发给该窗口        [DllImport("user32.dll")]    //屏蔽一个窗口客户区的全部或部分区域        public static extern int InvalidateRect(int hwnd, ref Rectangle lpRect, bool bErase);        private const int wMsg1 = 0x1026;        private const int wMsg2 = 0x1024;        private const uint lParam1 = 0xffffffff;        private const uint lParam2 = 0x00ffffff;        Rectangle lpRect = new Rectangle(0, 0, 0, 0);        public DeskTopIco304()        {            InitializeComponent();        }        private void button_setting_Click(object sender, EventArgs e)        {            int hwnd;            hwnd = GetDesktopWindow();            hwnd = FindWindowEx(hwnd, 0, "Progman", null);            hwnd = FindWindowEx(hwnd, 0, "SHELL_DefView", null);            hwnd = FindWindowEx(hwnd, 0, "SysListView32", null);            SendMessage(hwnd, wMsg1, 0, lParam1);            SendMessage(hwnd, wMsg2, 0, lParam2);            InvalidateRect(hwnd, ref lpRect, true);            MessageBox.Show("设置成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);        }    }}

四.鼠标相关

4.1设置输入法

InputLanguage类可以设置计算机的输入法

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace SystemSettings{    public partial class InputLanguage401 : Form    {        public InputLanguage401()        {            InitializeComponent();        }        private void comboBox_Setting_SelectedIndexChanged(object sender, EventArgs e)        {            //获取选择的输入法            InputLanguage mInput = InputLanguage.InstalledInputLanguages[comboBox_Setting.SelectedIndex];            //设置当前输入法            InputLanguage.CurrentInputLanguage = mInput;            //获取当前输入法信息            InputLanguage CurrentLanguage = InputLanguage.CurrentInputLanguage;            this.label_Current.Text = CurrentLanguage.LayoutName;            //设置输入法语言区域            this.label_LanguageAreaShow.Text = CurrentLanguage.Culture.DisplayName;            //获取默认输入法信息            InputLanguage dInput = InputLanguage.DefaultInputLanguage;            this.label_DefaultLanguage.Text = dInput.LayoutName;        }        private void InputLanguage401_Load(object sender, EventArgs e)        {            //获取已经安装的输入法列表            InputLanguageCollection mInputs = InputLanguage.InstalledInputLanguages;            foreach (InputLanguage mInput in mInputs)            { this.comboBox_Setting.Items.Add(mInput.LayoutName); }            //获取当前输入法信息            InputLanguage CurrentInput = InputLanguage.CurrentInputLanguage;            //获取当前输入法            this.label_Current.Text = CurrentInput.LayoutName;            //获取输入法区域            this.label_LanguageAreaShow.Text = CurrentInput.Culture.DisplayName;            //获取默认输入法            InputLanguage defaultlanguage = InputLanguage.DefaultInputLanguage;            this.label_DefaultLanguage.Text = defaultlanguage.LayoutName;        }    }}

4.2获取鼠标在任意点的颜色值

通过API函数获得指定坐标的颜色值来获取屏幕颜色的获取
CreateDC 为专门的设备创建设备场景
GetPixel获取设备场景中一个像素的RGB值

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace SystemSettings{    public partial class MouseRGB402 : Form    {        [DllImport("gdi32.dll")]        static public extern uint GetPixel(IntPtr hDC, int XPos, int YPos);        [DllImport("gdi32.dll")]        static public extern IntPtr CreateDC(string driverName, string deviceName, string output, IntPtr ipinitData);        [DllImport("gdi32.dll")]        static public extern bool DeleteDC(IntPtr DC);        static public byte GetRValue(uint color)        {            return (byte)color;        }        static public byte GetGValue(uint color)        {            return ((byte)((short)(color) >> 8));        }        static public byte GetBValue(uint color)        {            return ((byte)((color) >> 16));        }        static public byte GetAValue(uint color)        {            return ((byte)((color) >> 24));        }        public Color GetColor(Point screenpoint)        {            //创建一个屏幕句柄            IntPtr disPlayDC = CreateDC("DISPLAY", null, null, IntPtr.Zero);            //取得鼠标所在位置的RGB值            uint colorref = GetPixel(disPlayDC, screenpoint.X, screenpoint.Y);            //删除场景            DeleteDC(disPlayDC);            //获取R G B值            byte Red = GetRValue(colorref);            byte Green = GetGValue(colorref);            byte Blue = GetBValue(colorref);            return Color.FromArgb(Red, Green, Blue);        }        public MouseRGB402()        {            InitializeComponent();        }        private void timer1_Tick(object sender, EventArgs e)        {            //获取鼠标的位置            textBox_mouse.Text = Control.MousePosition.X.ToString() + "," + Control.MousePosition.Y.ToString();            //实例化point            Point pt = new Point(Control.MousePosition.X, Control.MousePosition.Y);            //获取鼠标位置颜色            Color cl = GetColor(pt);            //显示该颜色            pictureBox_show.BackColor = cl;            textBox_RGB.Text = cl.R + "," + cl.G + "," + cl.B;            textBox_color.Text = ColorTranslator.ToHtml(cl).ToString();            textBox_win.Text = ColorTranslator.ToWin32(cl).ToString();        }        private void checkBox_TopMost_MouseUp(object sender, MouseEventArgs e)        {            if (this.checkBox_TopMost.Checked)                this.TopMost = true;            else            {                this.TopMost = false;            }        }        private void MouseRGB402_Load(object sender, EventArgs e)        {            timer1.Start();        }    }}


4.3切换鼠标左右键

SwapMouseButton函数用于决定是否切换鼠标左右键
GetSystemMetrics函数返回与windows环境有关的信息

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace SystemSettings{    public partial class MouseTab403 : Form    {        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SwapMouseButton")]        public extern static int SwapMouseButton(int bSwap);        [System.Runtime.InteropServices.DllImport("user32.dll")]        public extern static int GetSystemMetrics(int nIndex);        const int SM_SWAPBUTTON = 23;        public MouseTab403()        {            InitializeComponent();        }        private void checkBox_mouse_CheckedChanged(object sender, EventArgs e)        {            if (this.checkBox_mouse.Checked)            {                SwapMouseButton(1);            }            else            {                SwapMouseButton(0);            }            if (GetSystemMetrics(SM_SWAPBUTTON) == 1)            {                MessageBox.Show("右键为主要功能键");            }            else            {                MessageBox.Show("恢复左键为主要功能键");            }        }    }}

4.4限制鼠标活动区域

将鼠标限制在一个固定的范围内

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace SystemSettings{    public partial class LimitMouseActive404 : Form    {        public LimitMouseActive404()        {            InitializeComponent();        }        private void 限制鼠标活动区域ToolStripMenuItem_Click(object sender, EventArgs e)        {            this.Cursor = new Cursor(Cursor.Handle);            Cursor.Position = new Point(this.Location.X, this.Location.Y);            Cursor.Clip = new Rectangle(this.Location, this.Size);//设置鼠标的活动区域        }        private void 取消限制ToolStripMenuItem_Click(object sender, EventArgs e)        {            Screen[] screens = Screen.AllScreens;                //获取显示的数组            this.Cursor = new Cursor(Cursor.Current.Handle);     //创建cursor对象            Cursor.Clip = screens[0].Bounds;                      //解除限制        }    }}


五.磁盘属性

5.1获取磁盘序列号

.NET相关的获取硬盘物理序列号的方法,主要分为使用WMI方式和API方式。但这些方法均可能有问题。
1.使用WMI方式,有的机器根本取不到硬盘序列号,有的方式在Vista下面会报错。
2.还可以使用另外一WMI方式,就是查询 PNPDeviceID 的 signature
使用WMI方式需要客户机开启WMI服务,但这个往往不能保证,所以使用这种方式有一定局限性。
3.最好的一种是使用API方式。
在网上找到一片资料,说使用 RING3调用 API DeviceIoControl()来获取硬盘信息,下面是原话:
硬盘序列号(Serial Number)不等于卷标号(Volume Name),后者虽然很容易得到,但是格式化分区后就会重写,不可靠。遗憾的是很多朋友往往分不清这一点。
要得到硬盘的物理序列号,可以通过WMI,也就是Win32_PhysicalMedia.SerialNumber。可惜的是Windows 98/ME的WMI并不支持这个类,访问时会出现异常。

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Management;namespace DiskSystem{    public partial class DiskSerialNumber101 : Form    {        public DiskSerialNumber101()        {            InitializeComponent();        }        private void DiskSerialNumber101_Load(object sender, EventArgs e)        {            textBox_DiskSerialNumber.Text = AtapiDevice.GetHddInfo(0).SerialNumber.ToString();            textBox_diskid.Text = AtapiDevice.GetHddInfo(0).ModuleNumber.ToString();        }    }}

5.2获取映射驱动器路径

主要是通过WMI查询获取映射驱动器

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Management;namespace DiskSystem{    public partial class Getmappeddrivepath102 : Form    {        public Getmappeddrivepath102()        {            InitializeComponent();        }        private void Getmappeddrivepath102_Load(object sender, EventArgs e)        {            listBox_gmdp.Items.Clear();            SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");            ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);            int i = 0;            foreach (ManagementObject mo in searcher.Get())            {                string DriveType;                DriveType = mo["DriveType"].ToString();                if (DriveType == "4")                {                    listBox_gmdp.Items.Add(mo["Name"].ToString());                }                i++;            }        }    }}

5.3判断驱动器类型

用WMI获取系统驱动器  通过DriveInfo类来判断驱动器的类型

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Management;using System.IO;namespace DiskSystem{    public partial class Determinethedrivetype103 : Form    {        public Determinethedrivetype103()        {            InitializeComponent();        }        private void comboBox_d_SelectedIndexChanged(object sender, EventArgs e)        {            string DriveType = "";            MessageBox.Show(comboBox_d.SelectedItem.ToString());            DriveInfo dinfo = new DriveInfo(comboBox_d.SelectedItem.ToString().Trim());            try            {                DriveType = dinfo.DriveType.ToString();                switch (DriveType)                {                    case "Unknown":                        textBox_show.Text = "未知设备";                        break;                    case "NoRootDirectory":                        textBox_show.Text = "未知分区";                        break;                    case "Removable":                        textBox_show.Text = "这是可移动磁盘";                        break;                    case "NetWork":                        textBox_show.Text = "这是网络驱动器";                        break;                    case "CDRun":                        textBox_show.Text = "这是光驱";                        break;                    case "Fixed":                        textBox_show.Text = "这是硬盘";                        break;                    default:                        textBox_show.Text = "这是未知类型";                        break;                }            }            catch            {            }        }        private void Determinethedrivetype103_Load(object sender, EventArgs e)        {            SelectQuery selectQueery = new SelectQuery("select * from win32_logicaldisk");            ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQueery);            foreach (ManagementObject mo in searcher.Get())            {                comboBox_d.Items.Add(mo["Name"].ToString());            }        }    }}

5.4获取所有逻辑驱动器

本例中获取驱动器的方法和前面的方式不一样
使用的是System.IO.Directory.GetLogicalDrives();

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace DiskSystem{    public partial class AllLogicalDrive104 : Form    {        public AllLogicalDrive104()        {            InitializeComponent();        }        private void AllLogicalDrive104_Load(object sender, EventArgs e)        {            string[] logicdrivces = System.IO.Directory.GetLogicalDrives();            for (int i = 0; i < logicdrivces.Length; i++)            {                listBox_show.Items.Add(logicdrivces[i]);            }        }    }}

六.磁盘设置

6.1取消磁盘共享

 本例子是通过进程调用其他进程来达到指定的目的

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace DiskSystem{    public partial class CancelDiskSharing201 : Form    {        public CancelDiskSharing201()        {            InitializeComponent();        }        private void button_setting_Click(object sender, EventArgs e)        {            System.Diagnostics.Process myProcess = new System.Diagnostics.Process();            myProcess.StartInfo.FileName = "cmd.exe";            myProcess.StartInfo.UseShellExecute = false;            myProcess.StartInfo.RedirectStandardInput = true;            myProcess.StartInfo.RedirectStandardOutput = true;            myProcess.StartInfo.RedirectStandardError = true;            myProcess.StartInfo.CreateNoWindow = true;            myProcess.Start();            myProcess.StandardInput.WriteLine("NET SHARE " + textBox_txt.Text.Trim() + "$/DEL");            MessageBox.Show("执行成功", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);        }        private void CancelDiskSharing201_Load(object sender, EventArgs e)        {        }    }}

6.2驱动器容量

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Management;using System.IO;namespace DiskSystem{    public partial class DriveCapacity202 : Form    {        public DriveCapacity202()        {            InitializeComponent();        }        private void DriveCapacity202_Load(object sender, EventArgs e)        {            SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");            ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);            foreach (ManagementObject disk in searcher.Get())            {                comboBox_show.Items.Add(disk["Name"].ToString());            }        }        private void comboBox_show_SelectedIndexChanged(object sender, EventArgs e)        {            try            {                DriveInfo dinfo = new DriveInfo(comboBox_show.SelectedItem.ToString().Trim());                textBox_totals.Text = "驱动器总容量为:" + ((dinfo.TotalSize / 1024) / 1024) + "M";                textBox_Remaining.Text = "驱动器剩余容量为:" + ((dinfo.TotalFreeSpace / 1024) / 1024) + "M";            }            catch            {            }        }    }}

6.3图标显示磁盘容量

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Management;using System.IO;namespace DiskSystem{    public partial class DiskCapacityWithChart203 : Form    {        public DiskCapacityWithChart203()        {            InitializeComponent();        }        private void DiskCapacityWithChart203_Load(object sender, EventArgs e)        {            SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");            ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);            foreach (ManagementObject disk in searcher.Get())            {                comboBox_show.Items.Add(disk["Name"].ToString());            }        }        private void comboBox_show_SelectedIndexChanged(object sender, EventArgs e)        {            try            {                DriveInfo dinfo = new DriveInfo(comboBox_show.SelectedItem.ToString().Trim());                float tsize = dinfo.TotalSize;                float fsize = dinfo.TotalFreeSpace;                Graphics graphics = this.CreateGraphics();                Pen pen1 = new Pen(Color.Red);                Brush brush1 = new SolidBrush(Color.WhiteSmoke);                Brush brush2 = new SolidBrush(Color.LimeGreen);                Brush brush3 = new SolidBrush(Color.RoyalBlue);                Font font1 = new Font("Courier New ", 16, FontStyle.Bold);                Font font2 = new Font("宋体", 9);                graphics.DrawString(comboBox_show.SelectedItem.ToString().Trim() + "磁盘容量分析", font1, brush2, new Point(60, 50));                float angle1 = Convert.ToSingle((360 * (Convert.ToSingle(fsize / 100000000000) / Convert.ToSingle(tsize / 100000000000))));                float angle2 = Convert.ToSingle((360 * (Convert.ToSingle(tsize - fsize) / 100000000000) / Convert.ToSingle(tsize / 100000000000)));                graphics.FillPie(brush2, 60, 80, 150, 150, 0, angle1);                graphics.FillPie(brush3, 60, 80, 150, 150, angle1, angle2);                graphics.DrawRectangle(pen1, 30, 235, 200, 50);                graphics.FillRectangle(brush2, 35, 245, 20, 10);                graphics.DrawString("磁盘剩余容量:" + dinfo.TotalSize / 1000 + "KB", font2, brush2, 55, 245);                graphics.DrawString("磁盘已用容量" + (dinfo.TotalSize - dinfo.TotalFreeSpace) / 1000 + "KB", font2, brush2, 55, 265);            }            catch            {            }        }    }}

6.4磁盘格式化

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.IO;using System.Management;using System.Runtime.InteropServices;namespace DiskSystem{    public partial class DiskFormat204 : Form    {        [DllImport("shell32.dll")]        private static extern int SHFormatDrive(IntPtr hWnd, int drive, long fmtID, int Options);        public const long SHF_ID_DEFAULT = 0xFFFF;        public DiskFormat204()        {            InitializeComponent();        }        private void comboBox_show_SelectedIndexChanged(object sender, EventArgs e)        {        }        private void DiskFormat204_Load(object sender, EventArgs e)        {            SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");            ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);            foreach (ManagementObject disk in searcher.Get())            {                comboBox_show.Items.Add(disk["Name"].ToString());            }        }        private void button_setting_Click(object sender, EventArgs e)        {            try            {                SHFormatDrive(this.Handle, comboBox_show.SelectedIndex, SHF_ID_DEFAULT, 0);                MessageBox.Show("格式化成功");            }            catch            {                MessageBox.Show("格式化失败");            }        }    }}

七.程序控制

7.1打开控制面板的程序               

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace ApplicationC{    public partial class ControlPanel101 : Form    {        public ControlPanel101()        {            InitializeComponent();        }        private void ControlPanel101_Load(object sender, EventArgs e)        {        }        private void comboBox_show_SelectedIndexChanged(object sender, EventArgs e)        {            string text = comboBox_show.SelectedItem.ToString().Trim();            string value = "";            switch (text)            {                case "系统属性":                    value = "sysdm.cpl";                    break;                case "网络连接":                    value = "ncpa.cpl";                    break;                case "显示属性":                    value = "desk.cpl";                    break;                case "鼠标属性":                    value = "main.cpl";                    break;                case "电源选项":                    value = "powercfg.cpl";                    break;                case "用户帐户":                    value = "nusrmgr.cpl";                    break;                case "安全中心":                    value = "wscui.cpl";                    break;                case "辅助功能选项":                    value = "access.cpl";                    break;                case "添加硬件向导":                    value = "hdwwiz.cpl";                    break;                case "Java控制面板":                    value = "javacpl.cpl";                    break;                case "自动更新配置":                    value = "wuaucpl.cpl ";                    break;                case "网络安装向导":                    value = "netsetup.cpl";                    break;                case "Internet属性":                    value = "inetcpl.cpl ";                    break;                case "声音与音频设置":                    value = "mmsys.cpl";                    break;                case "区域与语言设置":                    value = "intl.cpl";                    break;                case "游戏控制器设置":                    value = "joy.cpl ";                    break;                case "时间和日期属性":                    value = "timedate.cpl";                    break;                case "添加或删除程序":                    value = "appwiz.cpl";                    break;                case "nVidia控制面板":                    value = "firewall.cpl";                    break;                case "ODBC数据源管理器":                    value = "odbccp32.cpl";                    break;                case "Intel集成显卡设置":                    value = "igfxcpl.cpl";                    break;                case "Windows防火墙/ICS设置":                    value = "nvcpl.cpl";                    break;                default:                    value = "";                    break;            }            try            {                if (value != "" || value != null)                {                    System.Diagnostics.Process.Start(value);                }            }            catch            {                MessageBox.Show("系统文件丢失");            }        }    }}

7.2添加磁盘到托盘               

主要使用NotifyIcon控件

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace ApplicationC{    public partial class AddProgramToTheTray102 : Form    {        public AddProgramToTheTray102()        {            InitializeComponent();        }        private void AddProgramToTheTray102_Load(object sender, EventArgs e)        {            this.notifyIcon1.Icon = Properties.Resources.accerciser;            this.notifyIcon1.Visible = false;        }        private void button_NotifyIcon_Click(object sender, EventArgs e)        {            this.notifyIcon1.Visible = true;        }        private void 恢复ToolStripMenuItem_Click(object sender, EventArgs e)        {            this.notifyIcon1.Visible = false;        }    }}

7.3任务栏上不出现图标               

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace ApplicationC{    public partial class NoTaskbarIcon103 : Form    {        public NoTaskbarIcon103()        {            InitializeComponent();        }        private void button_setting_Click(object sender, EventArgs e)        {            MessageBox.Show("窗体的ShowInTaskbar属性可以用来控制程序是否在任务栏显示");        }        private void NoTaskbarIcon103_Load(object sender, EventArgs e)        {            this.Icon = Properties.Resources.accerciser;        }    }}

7.4调用外部EXE文件               

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace ApplicationC{    public partial class CallEXE104 : Form    {        public CallEXE104()        {            InitializeComponent();        }        private void button_CallEXE_Click(object sender, EventArgs e)        {            try            {                OpenFileDialog ofd = new OpenFileDialog();                ofd.Filter = "EXE文件(*.exe)|*.exe";                ofd.ShowDialog();                System.Diagnostics.Process.Start(ofd.FileName);            }            catch            {            }        }    }}

7.5关闭外部程序

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Diagnostics;namespace ApplicationC{    public partial class CloseProgram105 : Form    {        public CloseProgram105()        {            InitializeComponent();        }        private void CloseProgram105_Load(object sender, EventArgs e)        {            listBox_show.Items.Clear();            Process[] myProcess = Process.GetProcesses();            foreach (Process mp in myProcess)            {                if (mp.MainWindowTitle.Length > 0)                    listBox_show.Items.Add(mp.ProcessName.ToString().Trim());            }        }        private void button_close_Click(object sender, EventArgs e)        {            Process[] myProcesses = Process.GetProcessesByName(listBox_show.SelectedItem.ToString().Trim());            foreach (Process myProcess in myProcesses)            {                myProcess.CloseMainWindow();            }            listBox_show.Items.RemoveAt(listBox_show.SelectedIndex);            MessageBox.Show("该进程已关闭");        }    }}

八.程序运行
8.1防止程序多次运行               

Path类的GetFileNameWithoutExtension方法获得指定路径字符串的文件名,然后使用
Process类的GetProcessesByName方法创建一个Process类型数组,并将该数组与本地计算机上共享指定进程的所有进程相关的资源

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Diagnostics;using System.IO;namespace ApplicationC{    public partial class RunOnce201 : Form    {        public RunOnce201()        {            InitializeComponent();        }        private void RunOnce201_Load(object sender, EventArgs e)        {            string MName = Process.GetCurrentProcess().MainModule.ModuleName;            string PName = Path.GetFileNameWithoutExtension(MName);//返回指定字符串的文件名            Process[] myProcess = Process.GetProcessesByName(PName);//根据文件名创建进程资源数组            if (myProcess.Length > 1)            {                MessageBox.Show("本程序模块只能运行一次!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);                this.Close();            }        }    }}

8.2获取任务栏尺寸               

FindWindow可以用来返回任务栏所在类Shell_TrayWnd的句柄
GetWindowRect是windowAPI提供的拥有获得任意一个窗口的矩阵范围的函数

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace ApplicationC{    public partial class TaskbarSize202 : Form    {        [DllImport("user32.dll")]        public static extern int FindWindow(string ipClassName, string ipWindowName); //声明API函数FindWindow        [DllImport("user32.dll")]        public static extern int GetWindowRect(int hwnd, ref Rectangle ipRect);        Rectangle myrect;        public TaskbarSize202()        {            InitializeComponent();        }        private void TaskbarSize202_Load(object sender, EventArgs e)        {            if (GetWindowRect(FindWindow("Shell_TrayWnd", null), ref myrect) == 0)            {                return;            }            else            {                this.textBox_left.Text = Convert.ToString(myrect.Left);                this.textBox_right.Text = Convert.ToString(myrect.Right);                this.textBox_Bottom.Text = Convert.ToString(myrect.Bottom);                this.textBox_Top.Text = Convert.ToString(myrect.Top);            }        }    }}

8.3程序运行时禁止关机               

 windows系统关机时,它会给正在运行的应用程序发送一个WM_QUERYENDSESSION消息
,通知应用程序,系统即将关机,如果应用程序返回的消息为0 ,系统就不会关机 这样就能实现禁止
关机的目的:
重写了 WndProc

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace ApplicationC{    public partial class ProhibitionShutDown203 : Form    {        private int isClose = 0;                       //声明一个变量表示是否关机        private const int WM_QUERYENDSESSION = 0x0011; //系统发送的关机命令        protected override void WndProc(ref Message m) //此方法用于处理Windows消息        {            switch (m.Msg)            {                case WM_QUERYENDSESSION:                    m.Result = (IntPtr)isClose;                    break;                default:                    base.WndProc(ref m);                    break;            }        }        public ProhibitionShutDown203()        {            InitializeComponent();        }        private void button_AllowedShutdown_Click(object sender, EventArgs e)        {            isClose = 1;            MessageBox.Show("允许关机");        }        private void button_ProhibitionShutDown_Click(object sender, EventArgs e)        {            isClose = 0;            MessageBox.Show("禁止关机");        }    }}

8.4改变系统提示信息               

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace ApplicationC{    public partial class ChangeTheSystemMessage204 : Form    {        public ChangeTheSystemMessage204()        {            InitializeComponent();        }        private void ChangeTheSystemMessage204_Load(object sender, EventArgs e)        {            toolTip1.InitialDelay = 1000;            //设置显示之前经过的时间            toolTip1.ReshowDelay = 500;              //设置出现提示窗口出现的时间            toolTip1.ShowAlways = true;              //设置是否显示提示窗口            toolTip1.SetToolTip(this.groupBox_title, "提示有变化了吧"); //设置文本与控件关联        }    }}


8.5获取环境变量               

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Collections;namespace ApplicationC{    public partial class EnvironmentVariable205 : Form    {        public EnvironmentVariable205()        {            InitializeComponent();        }        private void EnvironmentVariable205_Load(object sender, EventArgs e)        {            listView_show.View = View.Details;                                //设置控件显示方式            listView_show.GridLines = true;                                   //是否显示网格            listView_show.Columns.Add("环境变量", 150, HorizontalAlignment.Left); //添加列表格            listView_show.Columns.Add("变量值", 150, HorizontalAlignment.Left);    //添加列表格            ListViewItem myItem;            foreach (DictionaryEntry DEntry in Environment.GetEnvironmentVariables())            {                myItem = new ListViewItem(DEntry.Key.ToString(), 0);                myItem.SubItems.Add(DEntry.Value.ToString());                listView_show.Items.Add(myItem);            }        }    }}

8.6启动屏幕保护

通过SendMessage向窗口发送消息来启动计算机屏幕保护程序

 

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace ApplicationC{    public partial class StartScreenSaver206 : Form    {        [DllImport("user32.dll")]        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);        private const int WM_SYSCOMMAND = 0x2062;        private const int SC_SCREENSAVE = 0xf140;        public StartScreenSaver206()        {            InitializeComponent();        }        private void button_StartScreenSaver_Click(object sender, EventArgs e)        {            //用消息启动屏幕保护程序            SendMessage(this.Handle, WM_SYSCOMMAND, SC_SCREENSAVE, 0);        }        private void StartScreenSaver206_Load(object sender, EventArgs e)        {        }    }}

本文源码下载  作者其他源码下载