我想捕获我的文本框并将其转换为PDF格式 我尝试了以下代码,但它捕获了整个屏幕。如何仅捕获文本框值?
代码:
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());
}
用于导出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();
答案 0 :(得分:1)
您不应该使用this.Bounds
而是使用yourTextBox.Bounds
。
答案 1 :(得分: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);
Dialog截图方法。使用任何Windows窗体的Handle属性获取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;
}