【问题标题】:how to break lines in textboxes in c# when send to printer发送到打印机时如何在c#中的文本框中换行
【发布时间】:2017-12-29 09:45:04
【问题描述】:

当我在文本框中输入一些文本时,我想在打印时将文本换行(1 行 7 个字符)。

代码如下

e.Graphics.DrawString(textBox24.Text, 
                      new Font("Arial", 12, FontStyle.Regular), 
                      Brushes.Black, 
                      new Point(32, 260));

我会怎么做?

【问题讨论】:

  • 在每 7 个字符后插入一个Environment.NewLine
  • 你能解释一下代码吗?
  • 哪些代码?你的代码?

标签: c# .net windows forms printing


【解决方案1】:

按照 oerkelens 的建议,在每 7 个字符处拆分并插入一个 Environment.NewLine。

public string GetPrintReadyString(string originalString)
{
    string result = ""
    for (var i = 0; i < originalString.Length; i += 7)
      result += (originalString.Substring(i, Math.Min(7, originalString.Length - i)) + Environment.NewLine);
    return result;
}

然后你可以通过传入你的字符串来调用这个方法:

e.Graphics.DrawString(GetPrintReadyString(textBox24.Text), 
                      new Font("Arial", 12, FontStyle.Regular), 
                      Brushes.Black, 
                      new Point(32, 260));

不要忘记任何异常处理,因为您的字符串来自用户输入。

编辑:如果您真的真的很想在一行中使用它,请将 textBox24.Text 替换为以下内容:

string.Join("", textBox24.Text.Select((c, i) => i > 0 && i % 7 == 0 ? string.Format(Environment.NewLine + c) : c.ToString()))

【讨论】:

  • 为什么是一行?你不需要一些异常处理吗?
【解决方案2】:

你可以这样做;

e.Graphics.DrawString(FormatText(textBox24.Text), 
                      new Font("Arial", 12, FontStyle.Regular), 
                      Brushes.Black, 
                      new Point(32, 260));

它使用这种方法。它循环遍历输入的字符串,每 7 个字符后插入一个新行

public string FormatText(string input)
{
    string returnText = "";
    int charCounter = 0;
    foreach(char c in input)
    {
        result += c;
        i++;
        if(i == 7)
        {
            result += Environment.NewLine;
            charCounter=0;
        }
    }
    return returnText;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    相关资源
    最近更新 更多