写一个可以winform保存窗体绘图并重新读取显示的程序
时间: 2023-03-20 22:02:08 浏览: 158
好的,以下是一个可以保存窗体绘图并重新读取显示的winform程序的示例:
```c#
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WinFormGraphicsDemo
{
public partial class MainForm : Form
{
private Bitmap _bitmap;
public MainForm()
{
InitializeComponent();
_bitmap = new Bitmap(ClientSize.Width, ClientSize.Height);
}
private void MainForm_Paint(object sender, PaintEventArgs e)
{
using (var graphics = Graphics.FromImage(_bitmap))
{
graphics.Clear(Color.White);
graphics.DrawLine(Pens.Black, new Point(0, 0), new Point(ClientSize.Width, ClientSize.Height));
graphics.DrawLine(Pens.Black, new Point(0, ClientSize.Height), new Point(ClientSize.Width, 0));
}
e.Graphics.DrawImage(_bitmap, 0, 0);
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Bitmap files (*.bmp)|*.bmp";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
_bitmap.Save(saveFileDialog.FileName);
}
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "Bitmap files (*.bmp)|*.bmp";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
_bitmap = new Bitmap(openFileDialog.FileName);
Invalidate();
}
}
}
}
}
```
在这个程序中,我们创建了一个名为“MainForm”的窗体,其中包含了一个可以绘制图形的画布,并且我们添加了“保存”和“打开”功能,可以让用户将绘制的图形保存到文件中,或者从文件中读取并显示出来。当用户绘制图形时,我们会将其保存到一个名为“_bitmap”的位图对象中,在窗体需要重新绘制时,我们会从该位图对象中读取图形并绘制到窗体上。
希望这个程序可以帮助到您!