/*****************************************/
/*★ Screen を Capture する 前田 稔 ★*/
/*****************************************/
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.Runtime.InteropServices;
class ConsoleMode
{
private const int SRCCOPY = 13369376;
private const int CAPTUREBLT = 1073741824;
private const int SW_HIDE = 0;
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("gdi32.dll")]
private static extern int BitBlt(IntPtr hDestDC,
int x, int y, int nWidth, int nHeight,
IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
[DllImport("user32.dll")]
private static extern IntPtr ReleaseDC(IntPtr hwnd, IntPtr hdc);
[DllImport("user32.dll")]
private static extern IntPtr GetWindowDC(IntPtr hwnd);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowRect(IntPtr hwnd, ref RECT lpRect);
[DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr handle, int command);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
/// <summary>
/// プライマリスクリーンの画像を取得する
/// </summary>
/// <returns>プライマリスクリーンの画像</returns>
public static Bitmap CaptureScreen()
{
IntPtr hWndHide = GetForegroundWindow();
//プライマリモニタのデバイスコンテキストを取得
IntPtr disDC = GetDC(IntPtr.Zero);
//Bitmapの作成
Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
//Graphicsの作成
Graphics g = Graphics.FromImage(bmp);
//Graphicsのデバイスコンテキストを取得
IntPtr hDC = g.GetHdc();
//この Window を隠す
ShowWindow(hWndHide, SW_HIDE);
System.Threading.Thread.Sleep(500);
//Bitmapに画像をコピーする
BitBlt(hDC, 0, 0, bmp.Width, bmp.Height, disDC, 0, 0, SRCCOPY);
//解放
g.ReleaseHdc(hDC);
g.Dispose();
ReleaseDC(IntPtr.Zero, disDC);
return bmp;
}
/// <summary>
/// アクティブなウィンドウの画像を取得する
/// </summary>
/// <returns>アクティブなウィンドウの画像</returns>
public static Bitmap CaptureActiveWindow()
{
//アクティブなウィンドウのデバイスコンテキストを取得
IntPtr hWnd = GetForegroundWindow();
IntPtr winDC = GetWindowDC(hWnd);
//ウィンドウの大きさを取得
RECT winRect = new RECT();
GetWindowRect(hWnd, ref winRect);
//Bitmapの作成
Bitmap bmp = new Bitmap(winRect.right - winRect.left,
winRect.bottom - winRect.top);
//Graphicsの作成
Graphics g = Graphics.FromImage(bmp);
//Graphicsのデバイスコンテキストを取得
IntPtr hDC = g.GetHdc();
//Bitmapに画像をコピーする
BitBlt(hDC, 0, 0, bmp.Width, bmp.Height, winDC, 0, 0, SRCCOPY);
//解放
g.ReleaseHdc(hDC);
g.Dispose();
ReleaseDC(hWnd, winDC);
return bmp;
}
public static int Main()
{
long nowTime = DateTime.Now.Ticks/1000000;
string str = "c:\\tmp\\s" + nowTime.ToString() + ".gif";
Bitmap bmp = CaptureScreen();
bmp.Save(str, ImageFormat.Gif);
return 0;
}
}
|