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.