Winform代码集

禁止除Ctrl+Alt+Del组合之外的所有输入,屏幕假死!

   #region 禁止除Ctrl+Alt+Del组合之外的所有输入,屏幕 假死!
        [DllImport("User32.dll")]
        public static extern bool BlockInput(bool enabled); //为真是假死
        #endregion

 

        #region 运行本地屏保
        private void RunScreenSaver()
        {
            String[] screenSavers = Directory.GetFiles(Environment.SystemDirectory, "*.scr");
            if (screenSavers.Length > 0)
            {// 启动获取到的第一个屏保
                Process.Start(new ProcessStartInfo(screenSavers[0]));
            }
        }
        #endregion

 

利用Dll屏蔽键盘del+ctrl+alt组合键

using System.Runtime.InteropServices;//命名空间

        [DllImport(@"native.dll", EntryPoint = "FuckSysKey")]
        private extern static bool FuckSysKey(bool enAble);

        private void button1_Click(object sender, EventArgs e)
        {
            FuckSysKey(false);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            FuckSysKey(true);
        }

 

载取屏幕
        private void GetImage()
        {
            try
            {
                string tempImagePath = Application.StartupPath;
                string temp = tempImagePath + "//MonitorImage ";
                Directory.CreateDirectory(@temp);
                Image i = new Bitmap(this.Width, this.Height);
                Graphics g = Graphics.FromImage(i);
                g.CopyFromScreen(new Point(this.Location.X, this.Location.Y), new Point(0, 0), new Size(this.Width, this.Height));
                i.Save(@temp + "//" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ".jpg");
                g.Dispose();
                CommonClass.MessageBoxOK("截图成功!");
            }
            catch
            {
                CommonClass.MessageBoxNo("截图失败!");
            }
        }

 

    #region ArrayList的示例应用
    /// 方法名:DelArraySame    
    /// 功能:   删除数组中重复的元素
    /// </summary>   
    /// <param name="TempArray">所要检查删除的数组</param>
    /// <returns>返回数组</returns>  
    public string[] DelArraySame(string[] TempArray)
    {         
        ArrayList nStr = new ArrayList();  
        for (int i = 0; i < TempArray.Length; i++)   
        {             
            if (!nStr.Contains(TempArray[i]))      
            {                
                nStr.Add(TempArray[i]);  
            }      
        }       
        string[] newStr = (string[])nStr.ToArray(typeof(string));  
        return newStr;
    }
    #endregion

 

    #region 哈希表的简单示例
    public void HashTableTest()
    {
        Hashtable ht = new Hashtable();
        ht.Add("测试四", "测试四的值");
        ht.Add("测试二", "测试二的值");
        ht.Add("测试三", "测试三的值");
        foreach (DictionaryEntry de in ht)
        {
            Response.Write("这是"+de.Key+"&nbsp"+de.Value+"<br/>");
        }
    }
    #endregion

 

    #region 定义及遍历枚举值
    public enum enumone
    {
        李先生,
        许先生,
        张小姐
    }

    public void test()
    {
        foreach (enumone st in System.Enum.GetValues(typeof(enumone)))
        {
            Response.Write(st+"<br/>");
        }
    }
    #endregion

 

        ///命名空间
        ///using System.Runtime.InteropServices;
        ///using System.Diagnostics;
        #region 注销、关闭、重启计算机
        [DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)]
        //ExitWindowsEx 函数
        private static extern int ExitWindowsEx(int uFlags, int dwReserved);
        public void zhuxiao() //注销
        {
            ExitWindowsEx(0, 0);
        }

        public void guanji()//关机
        {
            try
            {
                Process.Start("Shutdown.exe", " -s -t 0");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
       
        public void chongqi()//重启
        {
            try
            {
                Process.Start("shutdown.exe", " -r -t 0");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

 

        #region 关闭显示器
        public const uint WM_SYSCOMMAND = 0x0112;
        public const uint SC_MONITORPOWER = 0xF170;
        [DllImport("user32")]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, uint wParam, int lParam);

        private void button1_Click(object sender, EventArgs e)
        {
            CloseLCD(sender, e);//关闭显示器
        }

        public void CloseLCD(object sender, EventArgs e)
        {
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MONITORPOWER, 2);    // 2 为关闭显示器, -1则打开显示器
        }
        #endregion

 

        #region 打开关闭光驱
        /// <summary>
        /// 类构造方法中加//mciSendString("set cdaudio door open", null, 0, IntPtr.Zero);
        /// </summary>
        private bool CDOpen = true;
        [System.Runtime.InteropServices.DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
        protected static extern int mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLength, IntPtr hwndCallback);

        private void button1_Click(object sender, EventArgs e)
        {
            mciSendString("set cdaudio door open", null, 0, IntPtr.Zero);
            if (CDOpen == false)
            {
                mciSendString("set cdaudio door open", null, 0, IntPtr.Zero);
                CDOpen = true;
                this.button1.Text = "关闭光驱";
            }
            else
            {
                mciSendString("set cdaudio door closed", null, 0, IntPtr.Zero);
                CDOpen = false;
                this.button1.Text = "打开光驱";
            }
        }
        #endregion

 

        #region 设置系统时间 (需引用System.Runtime.InteropServices;)
        [DllImport("kernel32.dll")]
        private static extern bool SetLocalTime(ref SYSTEMTIME time);

        [StructLayout(LayoutKind.Sequential)]
        private struct SYSTEMTIME
        {
            public short year;
            public short month;
            public short dayOfWeek;
            public short day;
            public short hour;
            public short minute;
            public short second;
            public short milliseconds;
        }

        public static void SetDate(DateTime dt)
        {
            SYSTEMTIME st;
            st.year = (short)dt.Year;
            st.month = (short)dt.Month;
            st.dayOfWeek = (short)dt.DayOfWeek;
            st.day = (short)dt.Day;
            st.hour = (short)dt.Hour;
            st.minute = (short)dt.Minute;
            st.second = (short)dt.Second;
            st.milliseconds = (short)dt.Millisecond;
            SetLocalTime(ref st);
        }
        #endregion

 

       using System.Management; //需要在解决方案中引用System.Management.DLL文件

        /// <summary>
        /// 取CPU编号
        /// </summary>
        /// <returns></returns>
        public static string GetCpuID()
        {
            try
            {
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                string strCpuID = null;
                foreach (ManagementObject mo in moc)
                {
                    strCpuID = mo.Properties["ProcessorId"].Value.ToString();
                    break;
                }
                return strCpuID;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 取第一块硬盘编号
        /// </summary>
        /// <returns></returns>
        public static string GetHardDiskID()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                string strHardDiskID = null;
                foreach (ManagementObject mo in searcher.Get())
                {
                    strHardDiskID = mo["SerialNumber"].ToString().Trim();
                    break;
                }
                return strHardDiskID;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 获取网卡MAC地址
        /// </summary>
        /// <returns></returns>
        public static string GetNetCardMAC()
        {
            try
            {
                string stringMAC = "";
                ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection MOC = MC.GetInstances();
                foreach (ManagementObject MO in MOC)
                {
                    if ((bool)MO["IPEnabled"] == true)
                    {
                        stringMAC += MO["MACAddress"].ToString();

                    }
                }
                return stringMAC;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 获取硬盘信息的代码
        /// </summary>
        /// <param name="drvID"></param>
        /// <returns></returns>
        public static string GetVolOf(string drvID)
        {
            try
            {
                const int MAX_FILENAME_LEN = 256;
                int retVal = 0;
                int a = 0;
                int b = 0;
                string str1 = null;
                string str2 = null;
                int i = GetVolumeInformation(drvID + @":/", str1, MAX_FILENAME_LEN, ref retVal, a, b, str2, MAX_FILENAME_LEN);
                return retVal.ToString("x");
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 获取当前网卡IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetNetCardIP()
        {
            try
            {
                string stringIP = "";
                ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection MOC = MC.GetInstances();
                foreach (ManagementObject MO in MOC)
                {
                    if ((bool)MO["IPEnabled"] == true)
                    {
                        string[] IPAddresses = (string[])MO["IPAddress"];
                        if (IPAddresses.Length > 0)
                        {
                            stringIP = IPAddresses[0].ToString();
                        }
                    }
                }
                return stringIP;
            }
            catch
            {
                return "";
            }
        }

 

        #region 调用注册表返回本地串口
        /// <summary>
        /// 串口函数(方法需调用注册表,串口编程所用类)
        /// </summary>
        /// 使用命名空间:
        /// using System.Security;
        /// using System.Security.Permissions;
        /// <returns>返回此计算机串口数组</returns>
        public static string[] GetPortNames()//
        {
            RegistryKey localMachine = null;
            RegistryKey key2 = null;
            string[] textArray = null;//这里有个判断,判断该注册表项是否存在   
            new RegistryPermission(RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINE/HARDWARE/DEVICEMAP/SERIALCOMM").Assert();
            try
            {
                localMachine = Registry.LocalMachine;
                key2 = localMachine.OpenSubKey(@"HARDWARE/DEVICEMAP/SERIALCOMM", false);
                if (key2 != null)
                {
                    string[] valueNames = key2.GetValueNames();
                    textArray = new string[valueNames.Length];
                    for (int i = 0; i < valueNames.Length; i++)
                    {
                        textArray[i] = (string)key2.GetValue(valueNames[i]);
                    }
                }
            }
            finally
            {
                if (localMachine != null)
                {
                    localMachine.Close();
                } if (key2 != null)
                {
                    key2.Close();
                }
                CodeAccessPermission.RevertAssert();
            } if (textArray == null)
            {
                textArray = new string[0];
            }
            return textArray;
        }
        #endregion

 

        #region MDI子窗体实例化一次
        /// <summary>
        /// 名称:CheckChildOpenState
        /// 功能:用子窗体的Name进行判断是否已实例化,如果存在则将他激活
        /// </summary>
        /// <param name="MdiForm">容器窗体</param>
        /// <param name="ChildForm">子窗体</param>
        public static void CheckChildOpenState(Form MdiForm, Form ChildForm)
        {
            foreach (Form tempChildForm in MdiForm.MdiChildren)
            {
                if (tempChildForm.Name == ChildForm.Name.ToString())
                {
                    if (tempChildForm.WindowState == FormWindowState.Minimized)
                    {
                        tempChildForm.WindowState = FormWindowState.Normal;
                    }
                    tempChildForm.Activate();
                    return;
                }
            }
            ChildForm.MdiParent = MdiForm;
            ChildForm.Show();
        }
        #endregion

 

给DataGridVeiw行头加数字ID

private void DataGridVeiw1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, DataGridVeiw1.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), DataGridVeiw1.RowHeadersDefaultCellStyle.Font, rectangle, DataGridVeiw1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

你可能感兴趣的:(exception,String,object,null,button,WinForm)