Search code examples
c#.netwinformsscreenshot

Is CopyFromScreen a right way to get screenshots?


I am creating an app that takes a screenshot of the desktop at a certain interval of time.

Code:

String nme = "";
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(printscreen as Image);
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
nme = DateTime.Now.ToString();
printscreen.Save(@"F:\Temp\printScre.jpg", ImageFormat.Jpeg);
  1. Is CopyFromScreen a right way to get the screenshot of the desktop?
  2. If I want to send this screenshot to the remote server, then what should be the best way to do that?
  3. Should I do some compression before sending it, and if so what are the most efficient ways?

Solution

    1. Yes, it is right way
    2. There are a few possibilities. I recommend sending it via email or FTP (as it's simple in c#).
    3. No, personally I don't think you need additional compression. Your screenshots are already saved as JPEG, so they are already compressed.

    Code snippet for sending email with attachment:

    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient(YOUR SMTP SERVER ADDRESS);
    mail.From = new MailAddress(SENDER ADDRESS);
    mail.To.Add(RECEIVER ADDRESS);
    mail.Subject = "Test Mail - 1";
    mail.Body = "mail with attachment";
    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("YOURFILE");
    mail.Attachments.Add(attachment);
    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential(YOUR_SMTP_USER_NAME, YOUR_SMTP_PASSWORD);
    SmtpServer.EnableSsl = true;
    SmtpServer.Send(mail); 
    

    (based on this blog)

    Code snippet for FTP:

        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
        StreamReader sourceStream = new StreamReader("testfile.txt");
        byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();    
        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);    
        response.Close();
    

    (based on MSDN)