对话框控件:
ColorDialog:颜色选择对话框,让用户自行选择一种颜色,使用方法类似FontDialog
FontDialog:字体选择对话框,让用户自行选择一种字体(也可以选择字体颜色,需要在属性中将ShowColor设置为True)
使用方法:
private void button1_Click(object sender, EventArgs e) { DialogResult dr = fontDialog1.ShowDialog(); if (dr == DialogResult.OK) { richTextBox1.Font = fontDialog1.Font; richTextBox1.ForeColor = fontDialog1.Color; } }
FolderBrowserDialog:让用户选择文件夹(使用较少,仅仅提供一个路径)
OpenFileDialog:显示一个对话框,提示用户打开文件(需要用到流,引用System.IO命名空间)
Filter属性:设置筛选器,筛选特定的某些文件格式
openFileDialog1.FileName:获取或设置包含文件名在内的文件路径
使用方法:
private void button2_Click(object sender, EventArgs e) { openFileDialog1.Filter = "文本文件|*.txt"; DialogResult dr = openFileDialog1.ShowDialog(); if (dr == DialogResult.OK) { StreamReader sr = new StreamReader(openFileDialog1.FileName, System.Text.Encoding.Default); richTextBox1.Text = sr.ReadToEnd(); } }
SaveFileDialog:显示一个对话框,提示用户保存文件(同上类似,也需要用到流)
同样也可以用Filter属性设置筛选文件格式,也可以通过FileName设置默认文件名,最后需要用Flush方法才可以进行保存
使用方法:
private void button3_Click(object sender, EventArgs e) { saveFileDialog1.Filter = "文本文件|*.txt|Word|*.doc"; saveFileDialog1.FileName = "新建文本文档!!!"; DialogResult dr = saveFileDialog1.ShowDialog(); if (dr == DialogResult.OK) { label1.Text = saveFileDialog1.FileName; StreamWriter sw = new StreamWriter(saveFileDialog1.FileName); sw.Write(richTextBox1.Text); sw.Flush(); } }
打印控件:
printDocument:定义一个向打印机发送的对象,其余打印控件均需要在此基础上进行操作
使用到事件里面的PrintPage事件
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { Font f = new System.Drawing.Font("微软雅黑", 16); Brush b = new SolidBrush(Color.Black); e.Graphics.DrawString(richTextBox1.Text, f, b, 10, 20); }
PageSetupDialog:页面设置对话框
private void button1_Click(object sender, EventArgs e) { pageSetupDialog1.Document = printDocument1; pageSetupDialog1.ShowDialog(); }
PrintPreviewControl:打印预览(只包含文档部分,并且需要在窗体上分配空间)
private void button2_Click(object sender, EventArgs e) { printPreviewControl1.Document = printDocument1; }
PrintPreviewDialog:打印预览对话框
private void button2_Click(object sender, EventArgs e) { printPreviewDialog1.Document = printDocument1; printPreviewDialog1.ShowDialog(); }
PrintDialog:打印对话框(注意需要接收返回值为OK时 执行打印)
private void button3_Click(object sender, EventArgs e) { printDialog1.Document = printDocument1; DialogResult dr = printDialog1.ShowDialog(); if (dr == DialogResult.OK) { printDocument1.Print(); } }