1 private void btn_CutScreen_Click(object sender, EventArgs e)
2 {
3 if (pic_MainScreen.Image != null)
4 {
5 pic_MainScreen.Image.Dispose();
6 pic_MainScreen.Image = null;
7 //MessageBox.Show("ok");
8 }
9 System.IO.MemoryStream ms = new System.IO.MemoryStream();
10 Bitmap bit = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
11
12 Graphics g = Graphics.FromImage(bit);
13
14 g.CopyFromScreen(0, 0, 0, 0, bit.Size);
15 g.Dispose();
16
17 bit.Save(ms, ImageFormat.Jpeg);
18 bit.Save("d:\\test\\" + DateTime.Now.ToString("HHmmss") + ".jpg");
19 bit.Dispose();
20 this.pic_MainScreen.Image = Image.FromStream(ms);
21 ms.Close();
22 ms.Dispose();
23 }
上面是主要代码,点第一次"截图"按钮还正常,多点几次picturebox控件显示的图片就变成层叠的了.不知道问题出现在哪里,奇怪的是打断点测试,或者在"if语句中添加messagebox"后就是正常效果.怎么解决呢,效果如图,郁闷.
正常啊,你把这个程序显示截图的界面又截图在里面了,当然是层叠的了。你可以在每次截图前先把你的程序界面隐藏一下,截完了再把它显示出来就可以了的。你按钮里的代码改成这样的:
try
{
this.Hide();
if (pic_MainScreen.Image != null)
{
pic_MainScreen.Image.Dispose();
pic_MainScreen.Image = null;
//MessageBox.Show("ok");
}
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Bitmap bit = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(bit);
g.CopyFromScreen(0, 0, 0, 0, bit.Size);
g.Dispose();
bit.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
bit.Save("c:\\" + DateTime.Now.ToString("HHmmss") + ".jpg");
bit.Dispose();
this.pic_MainScreen.Image = Image.FromStream(ms);
ms.Close();
ms.Dispose();
}
finally
{
this.Show();
}
那么,我不能一边截图一边看显示么?就是不隐藏主程序
谢谢.
@微软fans: 你可以看啊,截的那一瞬间隐藏了,然后截了就显示着你看呗。
@LCM: 最后截图前让线程睡一会儿,要是有时候还是会截成重叠的。加一句
System.Threading.Thread.Sleep(100);