WinForm Tips for making gadgets

Source: Internet
Author: User

I. Common settings for form drawing

The setup of the form should be performed before the InitializeComponent () method in the form constructor

    public frmMain()    {        this.StartPosition = FormStartPosition.CenterScreen;//窗体居中显示 this.MaximizeBox = false;//不显示最大化按钮 this.FormBorderStyle = FormBorderStyle.FixedSingle;//禁止放大缩小 InitializeComponent(); }
Second, WinForm text box full selection function

Control_controladded event is registered before InitializeComponent () call

    PublicFrmmain ()    {This. controladded + =New System.Windows.Forms.ControlEventHandler (This. control_controladded); InitializeComponent (); }PrivatevoidControl_controladded (Object sender, ControlEventArgs e) {Bring the "future" into effect e.control.controladded + =New System.Windows.Forms.ControlEventHandler (This. control_controladded);Bring the "descendants" into effectforeach (Control cIn E.control.controls) {control_controladded (sender,new ControlEventArgs (c)); } //make "Past" effective textbox textbox = E.control as TextBox; if (textBox! = null) {textbox.keypress + = textbox_keypress;}} private void TextBox _keypress (object sender, KeyPressEventArgs e) {textbox textbox = Sender as TextBox; if (TextBox = null) return; if (E.keychar = = (char) 1) { Textbox.selectall (); e.handled = true;}           
Third, set a text box to display the log

First place a text box in the page, set the multiline=true and drag it to the appropriate size and then set it in the Load event

PrivateStaticint _maxlogmsgtextlength =10000;Maximum Log box inputPrivatevoidFrmmain_load (Object sender, EventArgs e) {This.txtLogMsg.Multiline =TrueMultiple selection, usually in the interface is set upThis.txtLogMsg.ScrollBars = scrollbars.vertical;Log output displays vertical scroll barsThis.txtLogMsg.ReadOnly =TrueOutput log Read-onlyThis.txtLogMsg.TextChanged + = txtlogmsg_textchanged;Registering a Change eventInt. TryParse (system.configuration.configurationmanager.appsettings["Max_logmsg_text_length"],Out _maxlogmsgtextlength);Priority to use configuration file configuration value}text box event to scroll the cursor to the end after appending the logvoidTxtlogmsg_textchanged (object sender, EventArgs e) {Txtlogmsg.selectionstart = txtLogMsg.Text.Length + ten;  Sets the length of text at which the selected text begins, and if the text length is exceeded, the default is the last of the text. Txtlogmsg.selectionlength = 0;  Sets the length of the selected text to 0 (moves the cursor to the end of the text) Txtlogmsg.scrolltocaret (); //Move scroll bar to cursor position} //Append log method AppendText debug directly in non-UI thread exception private void appendlogmsg (string msg) { //execute in UI thread Txtlogmsg.begininvoke (new Action () = {Txtlogmsg.appendtext (msg); Txtlogmsg.appendtext ( Environment.NewLine); //Append Line break}));             
Four, open a thread to perform the task

Avoid interface card death

var askThread=new Thread(() =>{  //TODO  //AppendLogMsg("添加日志,调试时不会报错~~~");}askThread.Start();//.NET Framework 4.5+//Task.Run(()=>{// //TODO//})
V. Open the Picture Selection dialog box

The default is multiple selection, return the selected file path collection, you can use the FirstOrDefault() method to determine whether the file is selected

Private list<String>Openimagesdialog (bool Ismulti = true) { var OpenFileDialog = new OpenFileDialog (); Const String imgexts = "image file (*.bmp;*.ico;*.gif;*.jpeg;*.jpg;*.png) |*.bmp;*.ico;*.gif;*.jpeg;*.jpg;*. PNG "; Openfiledialog.filter = imgexts; Openfiledialog.multiselect = Ismulti; Openfiledialog.restoredirectory = true; openfiledialog.filterindex = 1; var result = new list<string> (); if (openfiledialog.showdialog () = = DialogResult.OK) {result. AddRange (Openfiledialog.filenames); } return result;             
Vi. copying files to a specified directory

Copies the passed file to the specified directory and renames it with a GUID, the directory does not exist, and is automatically created using tuples to return the corresponding path key-value pairs (ITEM1) and the Failed Path collection (ITEM2)

///<summary>Copy files to the specified directory and rename them///</summary>///<param name= "Sourcepaths" > collection of File Paths to copy</param>///<param name= "TargetDir" > Target directory</param>///&LT;RETURNS&GT;ITEM1: Corresponding path, ITEM2: Failed file path</returns>PublicStatic tuple<dictionary<StringString>, list<String>> Copyfiletodir (list<String> Sourcepaths,String targetDir) {if (! Directory.Exists (TargetDir)) {directory.createdirectory (targetDir);}var errorfiles =New list<String> ();var savedirs = new dictionary< String, string> (); Sourcepaths.foreach (item = {// The path does not exist or the path already exists fails if (! File.exists (item) | | Savedirs.containskey (item)) {Errorfiles.add (item);} else {var savename = Guid.NewGuid () + Path.GetExtension (item); var Savepath = Path.Combine (TargetDir, savename); File.Copy (item, Savepath); Savedirs.add (item, Savepath); } }); var result = new tuple<dictionary< string, STRING>, List< String>> (Savedirs, errorfiles); return result;}            

Invocation example (appendlogmsg for append log method)

var selectImgs = OpenImagesDialog(true);//五、打开图片选择对话框方法var result = FileHelper.CopyFileToDir(selectImgs, txtSaveDir.Text);result.Item1.Keys.ToList().ForEach(item => AppendLogMsg(item + ":" + result.Item1[item]));//成功时输出result.Item2.ForEach(item => AppendLogMsg("文件复制失败:" + item));//文件错误输出
Vii. using INI file access configuration

Save some configuration to INI file, be your own tool for better flexibility

INI Operation class
PublicClassinihelper{Write operation function WritePrivateProfileString () of the declaration INI file [System.Runtime.InteropServices.DllImport ("Kernel32")]PrivateStaticexternLongWritePrivateProfileString (String section,String key,String Val,String filePath);The read operation function of the Declaration INI file getprivateprofilestring () [System.Runtime.InteropServices.DllImport ("Kernel32")]PrivateStaticexternIntGetPrivateProfileString (String section,String key,String Def, System.Text.StringBuilder RetVal,int size,String filePath);PrivateReadOnlyint _retlength =500;PrivateReadOnlyString _spath =Null///<summary>Initialize Inihelper///</summary>///<param name= "path" >ini File save path</param>///<param name= "RL" > Default 500</param>PublicInihelper (String path,Int? RL =NULL) {This._spath = path;This._retlength = RL. HasValue? Rl. Value: _retlength; }///<summary>Set INI configuration, default configuration section is setting///</summary>///<param name= "key" > Key Name</param>///<param name= "value" > key value</param>///<param name= "section" > Configuration Sections</param>PublicvoidWriteValue (String key,StringValuestring section ="Setting") {section= configuration section, key= key name, value= key value, path= path WritePrivateProfileString (sections, key,Value, _spath); }///<summary>Read the INI configuration according to the key honour point, the default node is setting///</summary>///<param name= "key" > Key Name</param>///<param name= "section" > Configuration Sections</param>  //<returns> </returns> public  string readvalue (string Key, string section = "Setting") { //each byte read from ini System.Text.StringBuilder temp = new System.text.s Tringbuilder (_retlength); //section= configuration section, key= key name, temp= above, path= path getprivateprofilestring (section, Key, "", temp, _retlength, _spath); return temp. ToString (); }}
Inihelper Use Example
string savePath = AppDomain.CurrentDomain.BaseDirectory + "config.ini";IniHelper _iniHelper = new IniHelper(savePath);//初始化_iniHelper.WriteValue("txtGitAddress");//写入_iniHelper.ReadValue("txtGitAddress");//读取
Other

To invoke a local program:System.Diagnostics.Process.Start("E:\\程序.exe", "c:\\windows");

WinForm Tips for making gadgets

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.