3

以下のコードとして CreateGraphics 関数を使用して、アクティブなフォーム (formMain) を印刷しています。

フォームの印刷 (Visual C#)

環境:クラシック モードの Windows 7 プロフェッショナル、VisuaStudio 2008

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern long BitBlt (IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
private Bitmap memoryImage;
private void CaptureScreen()
{
   Graphics mygraphics = this.CreateGraphics();
   Size s = this.Size;
   memoryImage = new Bitmap(s.Width, s.Height, mygraphics);
   Graphics memoryGraphics = Graphics.FromImage(memoryImage);
   IntPtr dc1 = mygraphics.GetHdc();
   IntPtr dc2 = memoryGraphics.GetHdc();
   BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
   mygraphics.ReleaseHdc(dc1);
   memoryGraphics.ReleaseHdc(dc2);
}
private void printDocument1_PrintPage(System.Object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
   e.Graphics.DrawImage(memoryImage, 0, 0);
}
private void printButton_Click(System.Object sender, System.EventArgs e)
{
   if (MessageBox.Show("test", "test", MessageBoxButtons.YesNo) == DialogResult.Yes)
   {
        CaptureScreen();
        printDocument1.Print();
   }
}

case1 : MessageBox がデフォルトの場所に表示される場合、formMain は明確に印刷できます 明らかに

ケース 2: ただし、マウスを使用して messageBox をデフォルトの場所から移動すると、印刷結果が汚れます。mainForm に messageBox (グラフ) が含まれるようになりました。

汚れた

4

2 に答える 2

1

WinAPI を直接使用する代わりに (BitBlt など)、これを使用してみてください。

Bitmap bmp = new Bitmap(this.Width, this.Height);
this.DrawToBitmap(bmp, this.Bounds);
bmp.Save(@"c:\temp\test.png", System.Drawing.Imaging.ImageFormat.Png); // For testing

これは、フォームのコンテンツのみを描画する必要があります。
これを別の最上位のフォームでテストし、成功しました。

コードに配置します。

private void CaptureScreen() {
    memoryImage = new Bitmap(this.Width, this.Height);
    this.DrawToBitmap(memoryImage, this.Bounds);
}
于 2013-08-12T08:39:05.683 に答える