如何获取一行中的字符数(Printing C#)
我已经有了这段代码,但它给了我错误的结果。
private void document_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int charPerLine = e.MarginBounds.Width / (int)e.Graphics.MeasureString("m", txtMain.Font).Width;
}
txtMain 是一个文本框。
I already have this code but it gives me the wrong result.
private void document_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int charPerLine = e.MarginBounds.Width / (int)e.Graphics.MeasureString("m", txtMain.Font).Width;
}
The txtMain is a textbox.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该可以解决问题。除以转换为整数的变量时要小心。如果
Width
属性小于 1,则您将被除以零,该值将被截断为零。您的应用程序中可能不太可能有这么小的字体,但这仍然是一个很好的做法。但真正的问题是为什么您甚至需要知道每行的字符数。除非您尝试进行某种 ASCII 艺术,否则您可以使用 Graphics.DrawString 的不同重载让 GDI+ 在边界矩形内为您布局文本,而无需知道有多少个字符适合一条线。
来自 MSDN 的此示例向您展示了如何执行此操作:
所以如果您是尝试打印一页文本,您只需将
drawRect
设置为e.MarginBounds
并为drawString
插入一页文本即可。另一件事,如果您尝试打印表格数据,您可以将页面划分为矩形 - 每列/行一个(但是您需要它),并使用
e.Graphics.DrawLine
重载来打印表格边框。如果您发布有关您实际想要实现的目标的更多详细信息,我们可以提供更多帮助。
This should do the trick. Be careful when dividing by a variable cast to an integer. You are leaving yourself open to a divide-by-zero here in the event that the
Width
property is less than one, which will be truncated to zero. It may be unlikely that you will have such a small font in your application, but it is still good practice.The real issue though is why do you even need to know the number of characters per line. Unless you are trying to do some sort of ASCII art, you can use the different overloads of
Graphics.DrawString
to have GDI+ layout the text for you inside a bounding rectangle without needing to know how many characters fit on a line.This sample from MSDN shows you how to do this:
So if you are trying to print a page of text, you can just set the
drawRect
to thee.MarginBounds
and plug a page worth of text in fordrawString
.Another thing, if you are trying to print tabular data, you can just partition the page into rectangles - one for each column/row (however you need it), and use
e.Graphics.DrawLine
overloads to print the table borders.If you post more details on what you are actually trying to achieve we can help more.