Bugster
Bugster

Reputation: 1594

Printing not working in Visual Studio 2008 Windows Forms Application

I tried printing a red rectangle in visual studio C++ 2008 using PrintDocument component, this is the code I used:

private:
   void printDocument1_PrintPage(System::Object ^ sender,
      System::Drawing::Printing::PrintPageEventArgs ^ e)
   {
      e->Graphics->FillRectangle(Brushes::Red,
         Rectangle(500, 500, 500, 500));
   }
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
         printDocument1->PrintPage += gcnew
         System::Drawing::Printing::PrintPageEventHandler
   (this, &Form1::printDocument1_PrintPage);
         }

I do have a printer and it works if you're wondering. The code above should print a red rectangle when a button is pressed, however it's not working. What am I doing wrong?

Upvotes: 0

Views: 553

Answers (1)

Hans Passant
Hans Passant

Reputation: 941217

The Click event handler is wrong, every click adds another event handler to PrintPage. That assignment belongs in the form constructor. It doesn't work because you forgot the important call, you didn't actually ask it to print. Fix:

    System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
        printDocument1->Print();
    }

Use PrintPreviewDialog to save a tree.

Upvotes: 1

Related Questions