Как получить изображение окна другого приложения? - C#
Формулировка задачи:
Здравствуйте, пытаюсь вывести изображение окна другого приложения, но ничего не происходит. В чем проблема?
Пишу на C# используя библиотеки win api
программа не идет дальше строки
IntPtr hDC, hSrcDC;
Rectangle rcSrc;
GetWindowRect(hWnd, out rcSrc);
hDC = GetDC(hWnd);
hSrcDC = CreateCompatibleDC((IntPtr)null);
Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rcSrc, ImageLockMode.ReadOnly, bmp.PixelFormat);
Bitmap newBitmap = new Bitmap(rcSrc.Right - rcSrc.Left, rcSrc.Bottom - rcSrc.Top, bmpData.Stride, bmp.PixelFormat, hDC);
bmp.UnlockBits(bmpData);
SelectObject(hSrcDC, newBitmap.GetHbitmap());
PrintWindow(hWnd, hSrcDC, 0);
BitBlt(
hDC,
0,
0,
rcSrc.Right - rcSrc.Left,
rcSrc.Bottom - rcSrc.Top,
hSrcDC,
0,
0,
TernaryRasterOperations.SRCCOPY);
pictureBox1.Image = newBitmap;Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");
Я пытаюсь вот этот метод написать на c# так, чтобы изображение в итоге было в Bitmap, но не выходит. Помогите плиз.
bool screen_shot_game(HWND window_f)
{
if(global_hunt!=NULL){
RECT rcSrc;
HWND hSrcWnd;
HDC hDC, hSrcDC;
HBITMAP hBmp;
GetWindowRect(window_f, &rcSrc);
hDC = GetDC(window_f);
hSrcDC = CreateCompatibleDC(NULL);
hBmp = CreateCompatibleBitmap(hDC, rcSrc.right - rcSrc.left, rcSrc.bottom - rcSrc.top);
SelectObject(hSrcDC, hBmp);
PrintWindow(window_f, hSrcDC, 0);
BitBlt(
hDC,
0,
0,
rcSrc.right - rcSrc.left,
rcSrc.bottom - rcSrc.top,
hSrcDC,
0,
0,
SRCCOPY);
StoreBitmapFile("3.bmp",hBmp);
DeleteObject(hBmp);
DeleteDC(hSrcDC);
ReleaseDC(global_hunt, hDC);
return true;
}
return false;
}Решение задачи: «Как получить изображение окна другого приложения?»
textual
Листинг программы
#region import
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
public override string ToString()
{
return string.Format("{0,4} {1,4} {2,4} {3,4}", Left, Top, Right, Bottom);
}
}
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetDC(IntPtr hWnd);
/// <summary>
/// Performs a bit-block transfer of the color data corresponding to a
/// rectangle of pixels from the specified source device context into
/// a destination device context.
/// </summary>
/// <param name="hdc">Handle to the destination device context.</param>
/// <param name="nXDest">The leftmost x-coordinate of the destination rectangle (in pixels).</param>
/// <param name="nYDest">The topmost y-coordinate of the destination rectangle (in pixels).</param>
/// <param name="nWidth">The width of the source and destination rectangles (in pixels).</param>
/// <param name="nHeight">The height of the source and the destination rectangles (in pixels).</param>
/// <param name="hdcSrc">Handle to the source device context.</param>
/// <param name="nXSrc">The leftmost x-coordinate of the source rectangle (in pixels).</param>
/// <param name="nYSrc">The topmost y-coordinate of the source rectangle (in pixels).</param>
/// <param name="dwRop">A raster-operation code.</param>
/// <returns>
/// <c>true</c> if the operation succeedes, <c>false</c> otherwise. To get extended error information, call <see cref="System.Runtime.InteropServices.Marshal.GetLastWin32Error"/>.
/// </returns>
[DllImport("gdi32.dll", EntryPoint = "BitBlt", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool BitBlt([In] IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, [In] IntPtr hdcSrc, int nXSrc, int nYSrc, TernaryRasterOperations dwRop);
public enum TernaryRasterOperations : uint
{
SRCCOPY = 0x00CC0020,
SRCPAINT = 0x00EE0086,
SRCAND = 0x008800C6,
SRCINVERT = 0x00660046,
SRCERASE = 0x00440328,
NOTSRCCOPY = 0x00330008,
NOTSRCERASE = 0x001100A6,
MERGECOPY = 0x00C000CA,
MERGEPAINT = 0x00BB0226,
PATCOPY = 0x00F00021,
PATPAINT = 0x00FB0A09,
PATINVERT = 0x005A0049,
DSTINVERT = 0x00550009,
BLACKNESS = 0x00000042,
WHITENESS = 0x00FF0062,
CAPTUREBLT = 0x40000000
}
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);
#endregion
public Form1()
{
InitializeComponent();
listBox1.MouseClick += listBox1_MouseClick;
button1.Click += btnSearchHwnd_Click;
}
List<IntPtr> ListHandles = new List<IntPtr>();
void listBox1_MouseClick(object sender, MouseEventArgs e)
{
IntPtr Handle = ListHandles[listBox1.SelectedIndex];
RECT rct;
if (!GetWindowRect(Handle, out rct))
{
MessageBox.Show("ERROR");
return;
}
MessageBox.Show(rct.ToString());
Size s = new System.Drawing.Size(rct.Right - rct.Left + 1, rct.Bottom - rct.Top + 1);
Bitmap bmp = new Bitmap(s.Width, s.Height);
Graphics g = System.Drawing.Graphics.FromImage(bmp);
IntPtr dc1 = g.GetHdc();
IntPtr dc2 = GetDC(Handle);
bool success = PrintWindow(Handle, dc2, 0);
if (!success)
{ MessageBox.Show("Неудача!"); return; }
MessageBox.Show(string.Format("{0} {1}", s.Width, s.Height));
BitBlt(dc1, 0, 0, s.Width, s.Height, dc2, 0, 0, TernaryRasterOperations.SRCCOPY);
g.ReleaseHdc(dc1);
bmp.Save("screen.bmp");
bmp.Dispose();
MessageBox.Show("Файл сохранен");
}
private void btnSearchHwnd_Click(object sender, EventArgs e)
{
EnumWindows((hWnd, lParam) =>
{
if ((IsWindowVisible(hWnd) && GetWindowTextLength(hWnd) != 0))
{
ListHandles.Add(hWnd);
listBox1.Items.Add(GetWindowText(hWnd));
}
return true;
}, IntPtr.Zero);
}
string GetWindowText(IntPtr hWnd)
{
int len = GetWindowTextLength(hWnd) + 1;
StringBuilder sb = new StringBuilder(len);
len = GetWindowText(hWnd, sb, len);
return sb.ToString(0, len);
}