WinForm 对话框【Dialog】

种类

  1. OpenFileDialog:打开文件对话框
  2. SavaFileDialog:保存文件对话框
  3. FontDialog:字体对话框
  4. ColorDialog:颜色选择对话框

应用

WinForm 对话框【Dialog】_第1张图片

  1. 点击【选择文件】按钮,将选取的文件内容写到文本框中
private void button1_Click(object sender, EventArgs e)
{
     
    // 弹出对话框
    OpenFileDialog o = new OpenFileDialog();
    // 标题
    o.Title = "请选择文件";
    // 多选
    o.Multiselect = true;
    // 初始目录
    o.InitialDirectory = @"C:\Users\lenovo\Desktop\";
    // 文件类型
    o.Filter = "文本文件|*.txt|图片文件|*.jpg|所有文件|*.*";
    // 展示
    o.ShowDialog();

    // 获取选中文件全路径
    string path = o.FileName;
    if (path == "")
    {
     
        return;
    }
    using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
    {
     
        byte[] buffer = new byte[1024 * 1024 * 5];
        // 实际读取到的字节数
        int r = fsRead.Read(buffer, 0, buffer.Length);
        // 解释字符串数组(0~r)
        textBox1.Text = Encoding.Default.GetString(buffer, 0, r);
    }
}
  1. 点击【保存】按钮,将文本框内容保存到指定文件中
private void button2_Click(object sender, EventArgs e)
{
     
    SaveFileDialog s = new SaveFileDialog();
    s.Title = "选择保存路径";
    s.InitialDirectory = @"C:\Users\lenovo\Desktop\";
    s.Filter = "文本文件|*.txt|图片文件|*.jpg|所有文件|*.*";
    s.ShowDialog();

    string path = s.FileName;

    if (path == "")
    {
     
        return;
    }

    using (FileStream f = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
    {
     
        byte[] buffer = Encoding.Default.GetBytes(textBox1.Text);
        f.Write(buffer,0,buffer.Length);
    }
}
  1. 字体设置
private void button3_Click(object sender, EventArgs e)
{
     
    FontDialog f = new FontDialog();
    f.ShowDialog();
    textBox1.Font = f.Font;
}


  1. 颜色设置
private void button4_Click(object sender, EventArgs e)
{
     
    ColorDialog c = new ColorDialog();
    c.ShowDialog();
    textBox1.ForeColor = c.Color;
}

你可能感兴趣的:(WinForm)