2011-09-23 131 views
6

我通过该代码捕获截图进行保存。通过C#发送屏幕截图

Graphics Grf; 
Bitmap Ekran = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppPArgb); 
Grf = Graphics.FromImage(Ekran); 
Grf.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); 
Ekran.Save("screen.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); 

然后发送该保存的屏幕截图作为电子邮件:

SmtpClient client = new SmtpClient(); 
MailMessage msg = new MailMessage(); 
msg.To.Add(kime); 
if (dosya != null) 
{ 
    Attachment eklenecekdosya = new Attachment(dosya); 
    msg.Attachments.Add(eklenecekdosya); 
} 
msg.From = new MailAddress("[email protected]", "Konu"); 
msg.Subject = konu; 
msg.IsBodyHtml = true; 
msg.Body = mesaj; 
msg.BodyEncoding = System.Text.Encoding.GetEncoding(1254); 
NetworkCredential guvenlikKarti = new NetworkCredential("[email protected]", "*****"); 
client.Credentials = guvenlikKarti; 
client.Port = 587; 
client.Host = "smtp.live.com"; 
client.EnableSsl = true; 
client.Send(msg); 

我想这样做:如何通过SMTP协议直接发送截图作为电子邮件没有保存?

回答

7

将位图保存为流。然后将流附加到您的邮件。例如:

System.IO.Stream stream = new System.IO.MemoryStream(); 
Ekran.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); 
stream.Position = 0; 
// later: 
Attachment attach = new Attachment(stream, "MyImage.jpg"); 
+3

记住围绕这些调用与使用块,这样你就不会出现内存泄漏,或致电.Dispose()方法来释放记忆。 – Digicoder

+0

对不起,我在编辑我的答案,当我最终发布时,我看到你的是一样的。你喜欢我删除我的吗? :)无论如何,+1为你 – Marco

+0

是的 - Digicoder提出了一个重要的观点。通过在所有IDisposable对象上使用“使用”块,可以改进原始代码。为了简单起见,我把它放在外面,而且正确设置“使用”块将需要修改所有原始代码。 –

2

使用此:

using (MemoryStream ms = new MemoryStream()) 
{ 
    Ekran.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
    using (Attachment att = new Attachment(ms, "attach_name")) 
    { 
     .... 
     client.Send(msg); 
    } 
} 
+0

别忘了附件也是一次性的...... –

+0

@詹姆斯:是的,你是对的:) – Marco