3

我想捕获我的文本框并将其转换为 PDF 格式。
我尝试了以下代码,但它捕获了整个屏幕。如何仅捕获我的文本框值?

  1. 代码:

    try
    {
        Rectangle bounds = this.Bounds;
        using (var bitmap = new Bitmap(bounds.Width, bounds.Height))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty,
                                 bounds.Size);
            }
            bitmap.Save("C://Rectangle.bmp", ImageFormat.Bmp);
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message.ToString());
    }
    
  2. 用于导出 pdf:

    captureScreen();
    var doc = new PdfDocument();
    var oPage = new PdfPage();
    doc.Pages.Add(oPage);
    oPage.Rotate = 90;
    XGraphics xgr = XGraphics.FromPdfPage(oPage);
    XImage img = XImage.FromFile(@"C://Rectangle.bmp");
    xgr.DrawImage(img, 0, 0);
    doc.Save("C://RectangleDocument.pdf");
    doc.Close();
    
4

2 回答 2

1

你不应该使用this.Boundsbut yourTextBox.Bounds

于 2012-10-12T11:57:08.723 回答
1

不是确切的解决方案,而是一些指向正确方向的提示。以下代码截取具有指定矩形的给定对话框的屏幕截图。您可以修改它以从客户区的屏幕截图中提取文本框(没有标题栏的对话框,...)

[StructLayout(LayoutKind.Sequential)]
public struct WINDOWINFO
{
    public UInt32 cbSize;
    public RECT rcWindow;
    public RECT rcClient;
    public UInt32 dwStyle;
    public UInt32 dwExStyle;
    public UInt32 dwWindowStatus;
    public UInt32 cxWindowBorders;
    public UInt32 cyWindowBorders;
    public UInt16 atomWindowType;
    public UInt16 wCreatorVersion;
}

通过 P/I 的一点原生魔法:

[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetWindowInfo(IntPtr hwnd, ref WINDOWINFO windowInfo);

[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, TernaryRasterOperations dwRop);

对话框截图方法。使用任何 Windows 窗体的 Handle-property 获取 hwnd。

protected Bitmap Capture(IntPtr hwnd, Rectangle rect)
{
    WINDOWINFO winInf = new WINDOWINFO();
    winInf.cbSize = (uint)Marshal.SizeOf(winInf);
    bool succ = PINativeOperator.GetWindowInfo(hwnd, ref winInf);

    if (!succ)
        return null;

    int width = winInf.rcClient.right - winInf.rcClient.left;
    int height = winInf.rcClient.bottom - winInf.rcClient.top;

    if (width == 0 || height == 0)
        return null;

    Graphics g = Graphics.FromHwnd(hwnd);
    IntPtr hdc = g.GetHdc();

    if(rect == Rectangle.Empty) {
        rect = new Rectangle(0, 0, width, height);
    }
    Bitmap bmp = new Bitmap(rect.Width, rect.Height);
    Graphics bmpG = Graphics.FromImage(bmp);
    PINativeOperator.BitBlt(bmpG.GetHdc(), 0, 0, rect.Width, rect.Height, hdc, rect.X, rect.Y, TernaryRasterOperations.SRCCOPY);
    bmpG.ReleaseHdc();

    return bmp;
}
于 2012-10-12T12:02:59.767 回答