简体   繁体   中英

C# - Printing the Form

I am using the code from MS to print a form however it looks like the form needs to be visible with a Show/ShowDialog() to work.

I am trying to use the code for a form that I don't want to show.

Any ideas?

可能可以使用DrawToBitmap方法。

If you are looking to print out data from the form in a relatively simple method, you might want to try this way instead. I use this method when I need to print something from a form. This uses a hidden WebBrowser control and works pretty good.

Sorry, the example is from a C++ project, but it converts nicely over to C#.

private: System::Void printButton_Click(System::Object^  sender, System::EventArgs^  e) {
        StringBuilder^ html = gcnew StringBuilder();

        html->Append( "<html><head></head><body>" );
        html->Append( "<h1>Children Clocked In</h1>" );

        html->Append( "<table>" );
        html->Append( "<tr><td>Last Name</td><td>First Name</td><td>Classroom</td><td>Program</td><td>In Time</td></tr>" );
        for each ( DataGridViewRow^ row in children->SelectedRows )
        {
            html->AppendFormat( "<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>",
                row->Cells[2]->Value->ToString(), 
                row->Cells[3]->Value->ToString(), 
                row->Cells[4]->Value->ToString(), 
                row->Cells[5]->Value->ToString(), 
                Convert::ToDateTime(row->Cells[6]->Value).ToString("h:mm tt") );
        }
        html->Append( "</table>" );

        html->Append( "</body></html>" );

        WebBrowser^ webBrowser = gcnew WebBrowser();
        webBrowser->Visible = false;
        webBrowser->Parent = this;
        webBrowser->DocumentCompleted += gcnew System::Windows::Forms::WebBrowserDocumentCompletedEventHandler(this, &FormChildrenClockedIn::webBrowser1_DocumentCompleted);
        webBrowser->DocumentText = html->ToString();
     } 
private: System::Void webBrowser1_DocumentCompleted(System::Object^  sender, System::Windows::Forms::WebBrowserDocumentCompletedEventArgs^  e) {
        ((WebBrowser^)sender)->ShowPrintPreviewDialog();
        delete (WebBrowser^)sender;
     }

Simplest way is to just open it somewhere outside the screen like

this.Position=new Point(-100000,-100000);

print it and then close it.

(don't forget about multiple monitors, that's why I used such big numbers).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM