VS.NET has been coming out for a long time, it feels ok. For a while, my friend made me write two print printers, and used a lot of conversations. When I saw the information, I saw a special article introduced the dialog box, I decided to write this article, let everyone Have a good start. At the same time, I also have to introduce some of the prints. You can study it carefully and have said a lot. Now we will develop! In the dialog, we often use the following: 1. File dialog (FileDialog) it is often used: Open File dialog (OpenFiledialog) Save File Dialogue (SavefileDialog) 2, Font Dialog (FontDialog) 3, Color Dialogue ColorDialog 4, Print Patch Dialog 5, Page Setup (PrintDialog) 6, print dialog (PrintDialog) is more, with time-time users can take a look at MSDN. Let's introduce one by one. In the process of introduction, I use a class of development: file, mainly the file operation.
File dialog (FileDialog)
First, open the file dialog (OpenFiledialog)
1, the OpenFileDialog control has the following basic properties
InitialDirectory dialog, the initial directory filter, file filter, for example, "text file (* .txt) | * .txt | file (*. *) || *. *" FilterIndex in the dialog box. The index of the file filter selected, if the first item is selected to the 1RESTOREDIRECTORY Control dialog box before being turned off, resume the current directory filename, the first file in the dialog, or the last selected file Title will be displayed in the conversation. Box Title Bar Auto Add Default Extension CheckPatHexists before the dialog returns, check the specified path to exist DefaultExt default extensions DereferenceLinks Whether to cancel the reference shortcut from the dialog box SHOWHELP Enable the "Help" ValidateNames Control Dialogue Box checks if the file name does not contain invalid characters or sequences
2, OpenFileDialog controls have the following common events
Fileok When the user hits the "Open" or "Save" button to handle the event HelpRequest to handle the event when the user clicks the "Help" button.
3, OpenFileDialog is as follows:
The following code can be used to implement the above dialog:
private void openFileDialogBTN_Click (object sender, System.EventArgs e) {OpenFileDialog openFileDialog = new OpenFileDialog (); openFileDialog.InitialDirectory = "c: //"; // Note that when the write path to use c: // instead of c: / OpenFileDialog.Filter = "Text file | *. * | C # file | * .cs | all files | *. *"; openfiledialog.restoreDirectory = true; OpenFileDialog.FilterIndex = 1; if (OpenFileDialog.showdialog () == DialogResult. OK) {fName = openFileDialog.FileName; File fileOpen = new File (fName); isFileHaveName = true; richTextBox1.Text = fileOpen.ReadFile (); richTextBox1.AppendText ( "");}} which is useful to File () class , I am in the program to perform file operations, write it yourself, at the end of this class. Interested netizens can analyze themselves.
Second, the save file dialog (SaveFileDialog) Save the file dialog control has two cases, one is saved, two is saving, saving is very simple, that is, writing a file in the case of the file, then writing a file, Here we mainly speak Saves (Saves). 1, the properties of the SaveFileDialog control
Filter To display the file filter shown in the dialog, for example, text file (*. *) | * .Txt | FilterIndex selected in the dialog box in the dialog box Index, if the first item is set to the 1RESTOREDIRECTORY Control dialog box before shutting down whether the current directory addExtension automatically adds the default extension checkacket checkpathexists Returns before the dialog returns, check the specified path whether there is a Container Control When you want to create a file, The user is prompted. Only when validatenames is true value. DefaultExt Default Extension DereferenceLinks Returning from the dialog Returns shortcut FileName First Initial DirewritEPRMPT Control when you want to overwrite the file in the dialog box or the last selected file InitialDirector dialog Prompt the user, only when ValidateNames is true value, only Showhelp Enable "Help" Title will display the character validatenames control dialog box in the dialog title bar to check if the file name does not contain invalid characters or sequences
2, the SavefileDialog event is as follows:
Fileok When the user hits the "Open" or "Save" button to handle the event HelpRequest to handle the event when the user clicks the "Help" button.
3, the effect of SavefileDialog is as follows:
4, can be implemented with the following code
private void saveAsDialogBTN_Click (object sender, System.EventArgs e) {SaveFileDialog saveFileDialog = new SaveFileDialog (); saveFileDialog.Filter = ". text file | * * | C # File | * .cs | All files | * *."; saveFileDialog. FilterIndex = 2; saveFileDialog.RestoreDirectory = true; if (saveFileDialog.ShowDialog () == DialogResult.OK) {if (saveFileDialog.ShowDialog () == DialogResult.OK) {fName = saveFileDialog.FileName; File fSaveAs = new File ( FNAME); isFileHavename = true; file: // Saved file has name fsaveas.writefile (richtextbox1.text);}}} In fact, these can be done directly in VS.NET IDE environments, in order to explain the problem, I am still a The list is also coming. Used in a File class library, the following is the source program: file.cs
using System; using System.IO; using System.Windows.Forms; using System.Text; namespace dialog {/// /// Summary description for File./// public class File {string fileName; public File (string fileName) {this.fileName = fileName;} public string ReadFile () {try {StreamReader sr = new StreamReader (fileName, Encoding.Default); string result = sr.ReadToEnd (); sr.Close (); return result;} catch ( Exception e) {MessageBox.Show (e.Message);} return null;} public void WriteFile (string str) {try {StreamWriter sw = new StreamWriter (fileName, false, Encoding.Default); sw.Write (str); SW.Close ();} catch (exception e) {messagebox.show (E.MESSAGE, "Save File Error!");}}}}
Font dialog (FontDialog) In text processing, we often use the font, now let's do a most common font dialog. First, Font Dialog (FontDialog) Common Properties
ShowColor Controls Whether the Color Options AllowScriptChange Display Fonts Fonts Font Fonts Fonts Fonts The font allowvertagers allows if the vertical Font Color Select the color fontmustexist When the font does not exist, the maximum name MINSIZE Optional Minimum Dictionary Scriptsonly Display Exemplary OEM and Symbol Font ShowApply Display "Apply" button Showeffects Whether to display the underscore, delete line, font color option showhelp Show "Help" button
Second, the font dialog (FontDialog) event
Apply When you click the "Apply" button, the event HelpRequest to be processed when you click the Help button.
Third, the effect of font dialog (FontDialog), implement code
private void fontDialogBTN_Click (object sender, System.EventArgs e) {FontDialog fontDialog = new FontDialog (); fontDialog.Color = richTextBox1.ForeColor; fontDialog.AllowScriptChange = true; fontDialog.ShowColor = true; if (fontDialog.ShowDialog () =! DialogResult.cancel) {richtextbox1.selectionFont = fontdialog.font; // Change the currently selected text}}
The above code sets the selected text to the font in the current FontDialog dialog. Color Dialog (ColorDialog) Color Pickup box is also one of our common dialogs, let's take a look at how to operate the color dialog in C #? First, Common Properties of Color Dialogs (Colordialog)
ALLOWFULLOPEN prohibits and enables the "Custom Color" button full of "Custom Color" partial "Custom Color" to the Dialog box Sworm SHOWHELP Displays the "Help" button Color in the dialog box in the dialog, AnyColor shows if any color customcolors displayed Define color SolidColorOnly can only choose solid color
Second, the color dialog (colorDialog) is as follows:
Third, see the code:
private void colorDialogBTN_Click (object sender, System.EventArgs e) {ColorDialog colorDialog = new ColorDialog (); colorDialog.AllowFullOpen = true; colorDialog.FullOpen = true; colorDialog.ShowHelp = true; colorDialog.Color = Color.Black; // initialize The font color in the current text box, when the user clicks on the "Cancel" button File: // restore the original value colordialog.showdialog (); richtextbox1.selectioncolor = colorDialog.color;}
Implementing the color dialog (colorDialog) is easy, in fact, not just a color dialog, C # is also very easy, as long as you go to learn, it is easy. After finishing the Color Dialog, we will talk to page settings.
Page Setup (PagesetupDialog)
In fact, the page setting (PagesetupDialog) doesn't have much, since talking about it, I still listed the properties used in PagesetupDialog.
First, page settings (PagesetupDialog) Common properties
AllowMargins Set whether you can use the "Direction" radio AllowPAper to set whether you can use the PrintDocumentMargins set by the printer settings to the paper size by editing the AllowPAper settings for the margin, how to use the "Printer" button Document Get the printer settings to allow users to choose the minimum margin
Second, the effect of the pagesetupdialog is as follows
It's so simple, let's take a look at it below, there is a more heavy stuff? About printing.
Printing Pretty and Print Printing is the function we often use in Windows programming. It is very troublesome before, but printing in Microsoft .NET Framework is used to use the component to use it, but it is still trouble, so Specially written for everyone to see. First, in the .NET environment, you can't say that PrintDocumet is called, PrintDocument belongs to System.Drawing.printing this name space, and PrintDocument This class is the core code that implements print. If you want to implement print, you must first construct the PrintDocument object to add a print event. PrintDocument.printPage = new printPageEventHandler (this.printDocument_printpage) Print is actually a method of calling the Graphics class for drawing, the following code is rewritten according to the routines provided on the MSDN. . MSDN print routine address: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdrawingprintingprintDocumentClasstopic.asp, interested netizens can see it. Here is the PrintDocument_printpage I have rewritten:
Private void printDocument_printpage (object sender, system.drawing.printing.printpageEventArgs e) {float linesperpage = 0; // Line number float ypos = 0; // Print the vertical position INT count = 0; // Ring counter Float leftmargin = E.Marginbounds.Left; // left side distance float topmargin = E.Marginbounds.top; // on the upper margin string line = null; // row string color clr = richtextbox1.selectionColor; // Current print color, In my program, I didn't implement different colors, Solidbrush B = New Solidbrush (CLR); // Brush fnt = richtextBox1.selectionFont; // Current print font linesperpage = E.Marginbounds.Height / Fnt.getHEight (E.Graphics); / / The number of rows that can be printed per page FILE: // Classified by line on a page while (count
{
YPOS = TopMargin (count * fnt.getheight (e.graphics));
E.Graphics.drawstring (Line, FNT, B, LEFTMARGIN, YPOS, New StringFormat ());
COUNT ;
}
File: // If the page prints complete, LINE does not have an empty note, there is a page that is not completed, issues the next print event,
File: // In the next print, LineReader will automatically read the last content without printing. LineReader can record the currently read location
IF (Line! = NULL)
E.hasmorepages = true;
Else
E.hasmorepages = false;
}
You can complete the entire print job here. After constructing PrintDocument_PrintPage, you can print and print your stay.
Second, the Print Hatching Dialog (PrintPreviewDialog) Print the Hatching a Hatch is used to display a print document after printing. In the Print Patch, you include, print, zoom, single page, or multiple pages, close, etc. The dialog is as follows:
The Print The Hatching dialog does not have much attribute, and finally calls with showdialog (). The above codes are as follows: private void printPreviewBTN_Click (object sender, System.EventArgs e) {lineReader = new StringReader (richTextBox1.Text); try {PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog (); printPreviewDialog1.Document = printDocument; printPreviewDialog1.FormBorderStyle = FormBorderStyle .Fixed3d; printpreviewdialog1.showdialog (this);} catch (Exception Excep) {MessageBox.show (Excep.Message, "Print error", MessageBoxButtons.ok, MessageBoxicon.Error; return;}}
Very simple, as long as you write PrintDocument_PrintPage (), it is easy.
Third, print dialog (PrintDialog) 1. Print dialog (PrintDialog) As long as you have the following properties:
ALLOWPRINTTOFILE prohibits or uses "Print to File" checkbox AllowSerection prohibits or uses "Selected Content" radio allowsOMEPages Disable or use the "page" radial button Document to get the printedocumentprinttoft to print to the file "checkbox" checkbox Showhelp Controls Whether to display the Help button SHOWNetwork Control Whether to display the Network button
2, the effect is as follows:
3, use the following code to achieve:
private void printDialogBTN_Click (object sender, System.EventArgs e) {PrintDialog printDialog = new PrintDialog (); printDialog.Document = printDocument; if (! printDialog.ShowDialog () = DialogResult.Cancel) {try {printDocument.Print ();} Catch (Exception EX) {MessageBox.show (EXMESSAGE);}}}
At this point, all the dialogs are finished, and the top capital is big. The above dialog box can be complete in the IDE environment of VS.NET. At this time, it will be separated by step. Summary In our tutorial, a total of file dialogs, font dialogs (FontDialog), Color dialogs (ColorDialog), Print PatchdpreviewDialog, Page Setup (PrintDialog), Print dialog ( PrintDialog, these dialogs, where the file dialog (FileDialog) is: Open the file dialog (OpenFileDialog, save the file dialog (Savefi Ledialog) two dialogs. With the above foundation, everyone can easily write a simple notepad.