Take a Screenshot on the CUWIN with Code

Applications, examples, and sample programs using products from Comfile Technology

Take a Screenshot on the CUWIN with Code

Postby Mike » Thu Aug 30, 2012 10:29 pm

This project shows how to take a screenshot from the CUWIN with code. You can also take screenshots using the "Remote Zoom In" tool installed with Visual Studio, but I found this method to be much more convenient especially when field testing.

Here's the most interesting part of the code, but you can download the project below if you want to actually see it in Action.
Code: Select all
enum RasterOperation : uint { SRC_COPY = 0x00CC0020 }

[DllImport("coredll.dll", SetLastError=true)]
static extern int BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, RasterOperation rasterOperation);

[DllImport("coredll.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);

[DllImport("coredll.dll")]
private static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);

private void TakeScreenshot()
{
    Rectangle bounds = Screen.PrimaryScreen.Bounds;
    IntPtr hdc = GetDC(IntPtr.Zero);
    if (hdc == IntPtr.Zero)
    {
        MessageBox.Show("Could not get DC");
        return;
    }

    try
    {
        //Take the screenshot
        Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format16bppRgb565);
        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            IntPtr dstHdc = graphics.GetHdc();
            try
            {
                if (BitBlt(dstHdc, 0, 0, bounds.Width, bounds.Height, hdc, 0, 0, RasterOperation.SRC_COPY) == 0)
                {
                    throw new Exception("BitBlt Failed");
                }
            }
            finally
            {
                graphics.ReleaseHdc(dstHdc);
            }
        }

        //Generate file name
        const string baseFilePath = "\\Flash Disk\\screenshot";
        const string fileExtension = ".jpg";
        string filePath = baseFilePath + fileExtension;
        int suffix = 1;
        while (File.Exists(filePath))
        {
            filePath = baseFilePath + suffix.ToString() + fileExtension;
            suffix++;
        }

        //Save to a file
        bitmap.Save(filePath, ImageFormat.Jpeg);
    }
    catch(Exception ex)
    {
        MessageBox.Show("Error: " + ex.Message);
    }
    finally
    {
        ReleaseDC(IntPtr.Zero, hdc);
    }
}


This project was built for the CUWIN V series, but should work on other CUWINs with little or no modification.
Attachments
CUWINScreenshotCSharp.zip
C# Project
(32.48 KiB) Downloaded 665 times
Mike
Mike
SuperDuperDuper
 
Posts: 551
Joined: Thu Mar 17, 2011 3:54 pm
Location: Seoul, South Korea

Return to Applications and Examples

Who is online

Users browsing this forum: No registered users and 2 guests

cron