我正在使用默认打印机打印多行文本框。我想通过使用 PrintDialog 来提供打印机选择。当我设置它时,会出现 PrintDialog 并且您选择一台打印机,但是当您按“确定”时,它总是会转到默认打印机。任何想法,将不胜感激。我已经包含了适当的代码。
private void printTreeViewToolStripMenuItem_Click(object sender, EventArgs e) //---added 6-29-12
{
textTreeView.Clear();
CreateRowsFromNode(treeView1.Nodes[0], 0, "");
//InitPrint(textTreeView.Text).Print();
printDialog1.Document = InitPrint(textTreeView.Text);
if (printDialog1.ShowDialog() == DialogResult.OK)
{
InitPrint(textTreeView.Text).Print();
}
}
最初没有PrintDialog,它只调用InitPrint(textTreeView.Text).Print()。如上所示添加了 printDialog1。
textTreeView 是要打印的 TextBox。textTreeView 文本框中的每一行都包含一个使用 CreateRowsFromNode 生成的节点文本值。
InitPrint 看起来像这样:
string TextToPrint; //---added 6-29-12
public PrintDocument InitPrint(string TextToPrint)
{
this.TextToPrint = TextToPrint;
PrintDocument PD = new PrintDocument();
PD.OriginAtMargins = true;
PD.DefaultPageSettings.Landscape = true; //---added 6-29-12
PD.PrintPage += PrintPage;
return PD;
}
public void PrintPage(object sender, PrintPageEventArgs e) //---added 6-29-12
{
int Chars = 0;
int Lines = 0;
Font Font = new Font("Courier new", 9);
//Font Font = new Font("Arial", 10);
Rectangle R = new Rectangle(Point.Empty, e.MarginBounds.Size);
StringFormat SF = StringFormat.GenericTypographic;
e.Graphics.MeasureString(TextToPrint, Font, R.Size, SF, out Chars, out Lines);
e.Graphics.DrawString(TextToPrint, Font, Brushes.Black, R, SF);
TextToPrint = TextToPrint.Substring(Chars);
e.HasMorePages = (TextToPrint.Length > 0);
}
将 TreeView 读入 textTreeView 的代码是:
private void CreateRowsFromNode(TreeNode node, int level, string L = "") //---added 6-29-12
{
string data = "";
string CurrentArrow = null;
string NextArrow = "";
//if root then no arrows needed
if (node.Parent == null) {
CurrentArrow = "";
NextArrow = "";
//if Not Last node of parent
}
else if (!(node.Parent.Nodes[node.Parent.Nodes.Count - 1] == node))
{
CurrentArrow = "├";
NextArrow = "│";
// is last node of parent
} else {
CurrentArrow = "└";
NextArrow = " ";
}
//Add the next node to the TextBox
if (node.Text.Length >= 115)
textTreeView.Text = textTreeView.Text + L + CurrentArrow + node.Text.Substring(0,115) + vbNewLine;
else
textTreeView.Text = textTreeView.Text + L + CurrentArrow + node.Text + vbNewLine;
//Add the Next Arrow to Left Part of string
L = L + NextArrow;
//Loop Through all its child nodes
foreach (TreeNode nod in node.Nodes) {
CreateRowsFromNode(nod, level + 1, L);
}
}