嘗試使用PrintDialog
,PrintDocument
和PrintPageEventHandler
類嘗試使用C#打印文檔時,出現特殊情況。爲什麼我的代碼在使用C#在橫向模式下打印時會後臺無限頁面?
每當我以橫向模式打印一串文本時,我的應用程序開始後臺打印無限數量的頁面,直到停止調試應用程序爲止。
以下是與點擊我的「打印」按鈕相對應的代碼。
private void button_print_Click(object sender, EventArgs e)
{
PrintDialog myPrintDialog = new PrintDialog();
PrintDocument myPrintDocument = new PrintDocument();
// assign the print document
myPrintDialog.Document = myPrintDocument;
// prompt the user with the dialog
if (myPrintDialog.ShowDialog() == DialogResult.OK)
{
StringReader myStringReader = new StringReader(this.rtb_results.Text);
myPrintDocument.PrintPage += new PrintPageEventHandler(myPrintDocument_PrintPage);
myPrintDocument.Print();
}
}
然後,這裏是對應於「打印頁面」事件的代碼...
void myPrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
StringReader myStringReader = null;
SolidBrush mySolidBrush = null;
String line = String.Empty;
Font myFont = null;
float linesPerPage = 0;
float leftMargin = 0;
float topMargin = 0;
float yPosition = 0;
int count = 0;
// assign the string-reader
myStringReader = new StringReader(this.rtb_results.Text);
// assign the brush type
mySolidBrush = new SolidBrush(Color.Black);
// assign the font
myFont = new Font("Consolas", 8.0F, FontStyle.Regular);
// assign the left margin
leftMargin = e.MarginBounds.Left;
// assign the top margin
topMargin = e.MarginBounds.Top;
// assign the number of lines per page
linesPerPage = e.MarginBounds.Height/myFont.GetHeight(e.Graphics);
while (count < linesPerPage && ((line = myStringReader.ReadLine()) != null))
{
yPosition = topMargin + (count * myFont.GetHeight(e.Graphics));
e.Graphics.DrawString(line, myFont, mySolidBrush, leftMargin, yPosition, new StringFormat());
count++;
}
if (line != null)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
// not sure why this would be here...
mySolidBrush.Dispose();
}
我在爲什麼這種奇怪的行爲可能發生的猜測,將有不似乎是任何限制右邊緣的東西(但這只是我的猜測)。我試圖用RectangleF
這個對象來測試這個理論,但我得到了同樣的結果......請讓我知道我做錯了什麼,如果有任何問題讓我知道。謝謝!
嗯,你必須返回HasMorePages的爲真,所以每次你myPrintDocument_PrintPage叫你重新啓動的所有進程,並開始在一開始的時候,你必須存儲位置當再次調用函數時,StreamReader再次尋求它 – Gusman
@Gusman爲什麼這對於縱向工作呢? – Snoopy
因爲它適合於一個頁面,並且您沒有將HasMorePages設置爲true,所以我的猜測是 – Gusman