У меня проблемы с снимком экрана с окном.
Это код, который я использую:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace Alerts
{
class ImgSearch
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow(string strClassName, string strWindowName);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle);
public struct Rect
{
public int Left { get; set; }
public int Top { get; set; }
public int Right { get; set; }
public int Bottom { get; set; }
}
public static void ScreenShotWindow(IntPtr whandle)
{
// Get the window rectangle
Rect window = new Rect();
GetWindowRect(whandle, ref window);
// Get window size
int width = window.Right - window.Left;
int height = window.Bottom - window.Top;
Size size = new Size();
size.Width = width;
size.Height = height;
//Create a new bitmap.
var bmpScreenshot = new Bitmap(width,
height,
PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);
// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(window.Left,
window.Right,
0,
0,
size,
CopyPixelOperation.SourceCopy);
// Save the screenshot to the specified path that the user has chosen.
bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);
}
}
}
Это результат:
Итак, как вы можете видеть, изображение пустое, и я ожидал получить изображение, подобное этому:
Я на 100% уверен, что дескриптор окна не проблема, потому что GetWindowRect работает отлично
Всего 1 ответ
В коде есть небольшая ошибка, которую легко пропустить.
gfxScreenshot.CopyFromScreen(window.Left,
window.Top, // window.Top instead of window.Right
0,
0,
size,
CopyPixelOperation.SourceCopy);
Вместо window.Right
вы должны использовать window.Top
здесь. Второй параметр - это координата Y области.