Skip to content

Instantly share code, notes, and snippets.

@gouf

gouf/Capture.cs Secret

Created February 4, 2022 05:50
Show Gist options
  • Save gouf/9a3200500268093872da9ca704fe75d5 to your computer and use it in GitHub Desktop.
Save gouf/9a3200500268093872da9ca704fe75d5 to your computer and use it in GitHub Desktop.
.NET C# で特定ウィンドウをキャプチャし、画像として保存する
namespace MyProgram;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
// 指定ウィンドウの座標情報を保持するのに使う
public struct Rect {
public int Left { get; set; }
public int Top { get; set; }
public int Right { get; set; }
public int Bottom { get; set; }
public int Height { get; set; }
public int Width { get; set; }
public double X { get; set; }
public double Y { get; set; }
}
public class Capture {
private IntPtr _ptr;
private Rect _rect;
public Capture() {
updateWindowRect();
}
// ゲーム画面全体をキャプチャ
public void gameWindow() {
Bitmap bitmap = new Bitmap(_rect.Right - _rect.Left, _rect.Bottom - _rect.Top);
Size size = new Size(_rect.Right - _rect.Left /* ヨコ, X */, _rect.Bottom - _rect.Top /* タテ, Y */);
String imageSavePath = @"C:\Users\my_name\MyProject\test.jpg";
captureArea(
_rect.Left, _rect.Top,
bitmap,
imageSavePath,
size
);
}
// BlueStacks 画面内のスクリーンキャプチャ
private void captureArea(int x, int y, Bitmap bitmap, String imageSavePath, Size blockRegionSize) {
// ウィンドウのフォアグラウンド制御。キャプチャ時にウィンドウが全面に表示されている必要がある
NativeMethods.SetForegroundWindow(_ptr);
// Bitmap bitmap = new Bitmap(size , size / 3 );
Graphics graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(
x, y,
0, 0,
blockRegionSize,
CopyPixelOperation.SourceCopy
);
bitmap.Save(imageSavePath, ImageFormat.Jpeg);
}
// プロセス取得
private Process getBlueStacksProcess() {
// NOTE: 取得できなかった場合 processes[0] で index 参照エラーが発生する
return Process.GetProcessesByName("hd-player")[0];
}
// ウィンドウ位置情報取得
private void setBlueStacksRect() {
NativeMethods.GetWindowRect(_ptr, ref _rect);
}
// ウィンドウ座標情報更新
public void updateWindowRect() {
_ptr = getBlueStacksProcess().MainWindowHandle;
NativeMethods.GetWindowRect(_ptr, ref _rect);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment