仅在C#中打印活动窗口

时间:2014-08-28 12:36:43

标签: c# printing screenshot scaling

我想只打印C#应用程序中的活动窗口。使用CopyFromScreen()不起作用,因为它需要截屏,并且窗口可以被出现的其他瞬态窗口部分隐藏。所以我尝试了PrintWindow():

private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
    e.Graphics.PageScale = 10.0f;
    Graphics g = e.Graphics;
    PrintWindow(this.Handle, g.GetHdc(), 0);
}

无论我使用哪种PageScale,都会产生一个很小的印章大小的窗口打印输出。 有什么想法吗?

EDIT 这就是诀窍:

private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
    Graphics myGraphics = CreateGraphics();
    var bitmap = new Bitmap(Width, Height, myGraphics);
    DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
    e.Graphics.DrawImage(bitmap, 0, 0);
}

1 个答案:

答案 0 :(得分:-1)

一些谷歌搜索,我发现:Copying content from a hidden or clipped window in XP?

您似乎需要准备一个用于存储页面的位图:

// Takes a snapshot of the window hwnd, stored in the memory device context hdcMem
HDC hdc = GetWindowDC(hwnd);
if (hdc)
{
    HDC hdcMem = CreateCompatibleDC(hdc);
    if (hdcMem)
    {
        RECT rc;
        GetWindowRect(hwnd, &rc);

        HBITMAP hbitmap = CreateCompatibleBitmap(hdc, RECTWIDTH(rc), RECTHEIGHT(rc));
        if (hbitmap)
        {
            SelectObject(hdcMem, hbitmap);

            PrintWindow(hwnd, hdcMem, 0);

            DeleteObject(hbitmap);
        }
        DeleteObject(hdcMem);
    }
    ReleaseDC(hwnd, hdc);
}