2014-04-18 28 views
-2

我有窗口的形式,但我想在windows窗體打印面板隱藏打印按鈕,這是我的代碼:如何在Windows窗體中打印面板?

private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) 
    { 
     System.Drawing.Image image = System.Drawing.Image.FromStream(this.streamToPrint); 
     int x = e.MarginBounds.X; 
     int y = e.MarginBounds.Y; 
     int width = image.Width; 
     int height = image.Height; 
     if ((width/e.MarginBounds.Width) > (height/e.MarginBounds.Height)) 
     { 
      width = e.MarginBounds.Width; 
      height = image.Height * e.MarginBounds.Width/image.Width; 
     } 
     else 
     { 
      height = e.MarginBounds.Height; 
      width = image.Width * e.MarginBounds.Height/image.Height; 
     } 
     System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, width, height); 
     e.Graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel); 
    } 

    public void StartPrint(Stream streamToPrint, string streamType) 
    { 
     this.printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage); 


     this.streamToPrint = streamToPrint; 
     this.streamType = streamType; 
     System.Windows.Forms.PrintDialog PrintDialog1 = new PrintDialog(); 
     PrintDialog1.AllowSomePages = true; 
     PrintDialog1.ShowHelp = true; 
     PrintDialog1.Document = printDoc; 

     DialogResult result = PrintDialog1.ShowDialog(); 
     if (result == DialogResult.OK) 
     { 
      printDoc.Print(); 
      //docToPrint.Print(); 
     } 

    } 

    private void button_Print_Certificate_Click(object sender, EventArgs e) 
    { 
      Graphics g1 = this.CreateGraphics(); 
     Image MyImage = new Bitmap(this.ClientRectangle.Width,  this.ClientRectangle.Height, g1); 
     Graphics g2 = Graphics.FromImage(MyImage); 
     IntPtr dc1 = g1.GetHdc(); 
     IntPtr dc2 = g2.GetHdc(); 
     BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376); 
     g1.ReleaseHdc(dc1); 
     g2.ReleaseHdc(dc2); 
     MyImage.Save(@"D:\PrintPage.jpg", ImageFormat.Jpeg); 
     FileStream fileStream = new FileStream(@"D:\PrintPage.jpg", FileMode.Open, FileAccess.Read); 
     StartPrint(fileStream, "Image"); 
     fileStream.Close(); 

     if (System.IO.File.Exists(@"D:\PrintPage.jpg")) 
     { 
      System.IO.File.Delete(@"D:\PrintPage.jpg"); 
     } 
    } 
+1

那麼問題是什麼?你在標題中提到的小組是如何相關的?你發佈的代碼與你想要的有什麼不同? –

+0

我想在我的winform中打印面板,但此代碼使用按鈕打印打印所有窗體 – user2717468

+0

嘗試用panel對象替換'button_Print_Certificate_Click'中所有出現的'this'。 –

回答

0

爲了打印一個特定的控制,你會希望使用該控件作爲源您的BitBlt操作。

因此,而不是this.CreateGraphics(),請致電panel.CreateGraphics()。同樣,使用panel.ClientRectangle來獲取圖像的寬度和高度。

但看看https://stackoverflow.com/a/597088/103167,這給你一個更簡單的方法。