winform制作小工具的技巧


在使用winfrom制作一些工具的時候,一些基本設置都是去屬性里面找來找去,一段時間就忘了,記錄記錄以備不時之需。

一、窗體繪制的常用設置

窗體的設置應當在窗體構造函數中InitializeComponent()方法前執行

    public frmMain()
    {
        this.StartPosition = FormStartPosition.CenterScreen;//窗體居中顯示  
        this.MaximizeBox = false;//不顯示最大化按鈕 
        this.FormBorderStyle = FormBorderStyle.FixedSingle;//禁止放大縮小 
        InitializeComponent();
    }

二、winform文本框全選功能

Control_ControlAdded事件在InitializeComponent()調用之前注冊

    public frmMain()
    {
        this.ControlAdded += new System.Windows.Forms.ControlEventHandler(this.Control_ControlAdded);
        InitializeComponent();
    }
    private void Control_ControlAdded(object sender, ControlEventArgs e)
    {
        //使“未來”生效
        e.Control.ControlAdded += new System.Windows.Forms.ControlEventHandler(this.Control_ControlAdded);
        //使“子孫”生效
        foreach (Control c in e.Control.Controls)
        {
            Control_ControlAdded(sender, new ControlEventArgs(c));
        }
        //使“過去”生效
        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;
        }
    }

三、設置一個顯示日志的文本框

首先在頁面中放置一個文本框,設置Multiline=true后拖動到合適大小
然后在加載事件中進行設置

private static int _maxLogmsgTextLength = 10000;//日志框最大輸入
private void frmMain_Load(object sender, EventArgs e)
{
    this.txtLogMsg.Multiline = true;//多選, 一般在界面中就設置了
    this.txtLogMsg.ScrollBars = ScrollBars.Vertical;//日志輸出顯示縱向滾動條
    this.txtLogMsg.ReadOnly = true; //輸出日志只讀
    this.txtLogMsg.TextChanged += txtLogMsg_TextChanged;//注冊改變事件
    int.TryParse(System.Configuration.ConfigurationManager.AppSettings["MAX_LOGMSG_TEXT_LENGTH"], out _maxLogmsgTextLength);//優先使用配置文件配置的值
}
//文本框事件 使追加日志后滾動光標到末尾
void txtLogMsg_TextChanged(object sender, EventArgs e)
{
    txtLogMsg.SelectionStart = txtLogMsg.Text.Length + 10;//設置選中文字的開始位置為文本框的文字的長度,如果超過了文本長度,則默認為文本的最后。
    txtLogMsg.SelectionLength = 0;//設置被選中文字的長度為0(將光標移動到文字最后)
    txtLogMsg.ScrollToCaret();//將滾動條移動到光標位置
}
//追加日志方法 在非UI線程中直接AppendText調試會異常
private void AppendLogMsg(string msg)
{
    //在UI線程中執行
    txtLogMsg.BeginInvoke(new Action(() =>
    {
        txtLogMsg.AppendText(msg);
        txtLogMsg.AppendText(Environment.NewLine);//追加換行符
    }));
}

四、開啟一個線程執行任務

避免界面卡死

var askThread=new Thread(() =>
{
  //TODO
  //AppendLogMsg("添加日志,調試時不會報錯~~~");
}
askThread.Start();
//.NET Framework 4.5+
//Task.Run(()=>{
//  //TODO
//})

五、打開圖片選擇對話框

默認為多選,返回選擇的文件路徑集合,可使用FirstOrDefault()方法判斷是否選擇了文件

private List<string> OpenImagesDialog(bool isMulti = true)
{
    var openFileDialog = new OpenFileDialog();
    const string imgExts = "圖像文件 (*.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;
}

六、復制文件到指定目錄

將傳遞的文件復制到指定目錄並以Guid重命名,目錄不存在則自動創建
使用元組返回對應路徑鍵值對(Item1)及失敗路徑集合(Item2)

/// <summary>
/// 復制文件到指定目錄並重命名
/// </summary>
/// <param name="sourcePaths">要復制的文件路徑集合</param>
/// <param name="targetDir">目標目錄</param>
/// <returns>Item1:對應路徑,Item2:失敗文件路徑</returns>
public static Tuple<Dictionary<string, string>, 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 =>
    {
        //路徑不存在或者路徑已存在則失敗
        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;
}

調用示例 ( AppendLogMsg 為追加日志方法)

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));//文件錯誤輸出

七、使用Ini文件存取配置

保存一些配置到ini文件,是自己的工具更佳靈活

ini操作類

public class IniHelper
{
    // 聲明INI文件的寫操作函數 WritePrivateProfileString()
    [System.Runtime.InteropServices.DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

    // 聲明INI文件的讀操作函數 GetPrivateProfileString()
    [System.Runtime.InteropServices.DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);

    private readonly int _retLength = 500;
    private readonly string _sPath = null;
    /// <summary>
    /// 初始化IniHelper
    /// </summary>
    /// <param name="path">ini文件保存路徑</param>
    /// <param name="rl">默認500</param>
    public IniHelper(string path, int? rl = null)
    {
        this._sPath = path;
        this._retLength = rl.HasValue ? rl.Value : _retLength;
    }
    /// <summary>
    /// 設置Ini配置,默認配置節為Setting
    /// </summary>
    /// <param name="key">鍵名</param>
    /// <param name="value">鍵值</param>
    /// <param name="section">配置節</param>
    public void WriteValue(string key, string value, string section = "Setting")
    {
        // section=配置節,key=鍵名,value=鍵值,path=路徑
        WritePrivateProfileString(section, key, value, _sPath);
    }
    /// <summary>
    /// 根據鍵名節點讀取Ini配置,默認節點為Setting
    /// </summary>
    /// <param name="key">鍵名</param>
    /// <param name="section">配置節</param>
    /// <returns></returns>
    public string ReadValue(string key, string section = "Setting")
    {
        // 每次從ini中讀取多少字節
        System.Text.StringBuilder temp = new System.Text.StringBuilder(_retLength);
        // section=配置節,key=鍵名,temp=上面,path=路徑
        GetPrivateProfileString(section, key, "", temp, _retLength, _sPath);
        return temp.ToString();
    }
}

IniHelper使用示例

string savePath = AppDomain.CurrentDomain.BaseDirectory + "config.ini";
IniHelper _iniHelper = new IniHelper(savePath);//初始化
_iniHelper.WriteValue("txtGitAddress");//寫入
_iniHelper.ReadValue("txtGitAddress");//讀取

其他

調用本地程序:System.Diagnostics.Process.Start("E:\\程序.exe", "c:\\windows");
打開目錄:System.Diagnostics.Process.Start("Explorer.exe", “目錄路徑E:\abc\”);

工具示例

Coding :https://coding.net/u/yimocoding/p/ImgsDownloadClient/git
Github :https://github.com/yimogit/ImgsDownloadClient


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM