C# WinForm 小技巧

1.窗体页面按键判断
   (1)单键判断
      if (e.KeyCode == Keys.Delete)
       {
         //处理逻辑
       } 
   (2)组合建判断:  
      if (e.Modifiers.CompareTo(Keys.Control) == 0 && e.KeyCode == Keys.Delete)
      {
       //处理逻辑
      }

2.C#WinForm的密码输入框禁止粘贴和右键
       private void LoginForm_Load(object sender, EventArgs e)
        {
            txtPassword.ContextMenu = new ContextMenu();
            txtPassword.KeyPress += new KeyPressEventHandler(txtPassword_KeyPress);
        }

        void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == 22)
            {
                e.Handled = true;
            }
        }

3.    拷贝文件夹(递归)

        //要拷贝的文件路径
          string dataFileName="";
        //指定文件路径的目录信息
          DirectoryInfo source = new DirectoryInfo(Path.GetDirectoryName(dataFileName));
        //本地文件路径
         string localFilePath = "C:\\temp\\";
        //本地文件目录
        DirectoryInfo localDirectory = new DirectoryInfo(localFilePath);
     
         /// <summary>
        /// 拷贝文件夹()
        /// </summary>
        /// <param name="source">要拷贝指定文件目录信息</param>
        /// <param name="destination">本地文件目录信息</param>
        private void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
        {            
            if (!destination.Exists) {
                destination.Create();
            }
            FileInfo[] files = source.GetFiles();
            foreach (FileInfo file in files)
            {
                file.CopyTo(Path.Combine(destination.FullName, file.Name));
            }
            DirectoryInfo[] dirs = source.GetDirectories();
            foreach (DirectoryInfo dir in dirs)
            {                           
                string destinationDir = Path.Combine(destination.FullName, dir.Name);                         
                CopyDirectory(dir, new DirectoryInfo(destinationDir));
            }
        }

 4. 获取资源文件(Xml)--要在同一命名空间下获取
     XmlDocument myXml = new XmlDocument();           
     string fileName = "AdminClient.Resources.bpmsCodes.xml";
     Assembly asm = Assembly.GetExecutingAssembly();//读取嵌入式资源
     Stream strm = asm.GetManifestResourceStream(fileName);
     myXml.Load(strm);//读取指定的XML文档

5.设置窗体的初始位置
      this.StartPosition = FormStartPosition.Manual; //必须先设置这个属性
      this.Location = = new Point(this.pointX, this.pointY + this.InputControl.Height + 30);
 

posted @ 2011-06-09 10:57  Michelle 米雪儿  阅读(403)  评论(0编辑  收藏  举报