PC からスクリーンショットを取得する関数がありますが、残念ながらメイン UI がブロックされるため、非同期の [スレッド呼び出し] を行うことにしました;ただし、ビットマップを返す前にスレッドの結果を待つのに問題があります。
これが私のコードです:
/// <summary>
/// Asynchronously uses the snapshot method to get a shot from the screen.
/// </summary>
/// <returns> A snapshot from the screen.</returns>
private Bitmap SnapshotAsync()
{
Bitmap image = null;
new Thread(() => image = Snapshot()).Start();
while (image == null)
{
new Thread(() => Thread.Sleep(500)).Start(); //Here i create new thread to wait but i don't think this is a good way at all.
}
return image;
}
/// <summary>
/// Takes a screen shots from the computer.
/// </summary>
/// <returns> A snapshot from the screen.</returns>
private Bitmap Snapshot()
{
var sx = Screen.PrimaryScreen.Bounds.Width;
var sy = Screen.PrimaryScreen.Bounds.Height;
var shot = new Bitmap(sx, sy, PixelFormat.Format32bppArgb);
var gfx = Graphics.FromImage(shot);
gfx.CopyFromScreen(0, 0, 0, 0, new Size(sx, sy));
return shot;
}
上記の方法は私が望むように非同期で動作していますが、改善できると確信しています。特に、何百ものスレッドを実行して結果を待つ方法は、良くないと確信しています。
ですから、コードを見て、それを改善する方法を教えてくれる人が本当に必要です。
[注: .NET 3.5 を使用しています]
そして、前もって感謝します。
ここで Eve と SiLo の助けを借りて解決された問題は、最良の 2 つの回答です
- 1 :
> private void TakeScreenshot_Click(object sender, EventArgs e)
> {
> TakeScreenshotAsync(OnScreenshotTaken);
> }
>
> private static void OnScreenshotTaken(Bitmap screenshot)
> {
> using (screenshot)
> screenshot.Save("screenshot.png", ImageFormat.Png);
> }
>
> private static void TakeScreenshotAsync(Action<Bitmap> callback)
> {
> var screenRect = Screen.PrimaryScreen.Bounds;
> TakeScreenshotAsync(screenRect, callback);
> }
>
> private static void TakeScreenshotAsync(Rectangle bounds, Action<Bitmap> callback)
> {
> var screenshot = new Bitmap(bounds.Width, bounds.Height,
> PixelFormat.Format32bppArgb);
>
> ThreadPool.QueueUserWorkItem((state) =>
> {
> using (var g = Graphics.FromImage(screenshot))
> g.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size);
>
> if (callback != null)
> callback(screenshot);
> });
> }
- 2 :
> void SnapshotAsync(Action<Bitmap> callback)
> {
> new Thread(Snapshot) {IsBackground = true}.Start(callback);
> }
> void Snapshot(object callback)
> {
> var action = callback as Action<Bitmap>;
> var sx = Screen.PrimaryScreen.Bounds.Width;
> var sy = Screen.PrimaryScreen.Bounds.Height;
> var shot = new Bitmap(sx, sy, PixelFormat.Format32bppArgb);
> var gfx = Graphics.FromImage(shot);
> gfx.CopyFromScreen(0, 0, 0, 0, new Size(sx, sy));
> action(shot);
> }
ボタンのクリックなどの使用法:
void button1_Click(object sender, EventArgs e) { SnapshotAsync(bitmap => MessageBox.Show("Copy successful!")); }