Visual C # dialog box full contact

Source: Internet
Author: User

It's been a long time since VS.net bate 2 came out. A while ago, my friend asked me to write two print programs for him, which used a lot of conversations. When I checked the information, I saw a special article about the dialog box outside China, I decided to write this article to give everyone a good start. At the same time, I also introduced the printed part. You can take a closer look and talk a lot about it. Now let's develop it!

In the dialog box, we often use the following types:

1. The file dialog box (FileDialog) is commonly used in two ways:

Open File Dialog Box (OpenFileDialog)

SaveFileDialog)

2. FontDialog)

3. Color dialog box (ColorDialog)

4. Print the Pre-Export Dialog Box (PrintPreviewDialog)

5. Page settings (PrintDialog)

6. Print the dialog box (PrintDialog)

For more information, see MSDN. Next we will introduce them one by one. During the introduction, I used a self-developed class: File, mainly for File operations.

  File Dialog Box (FileDialog)

  1. open the file dialog box (OpenFileDialog)

1. The OpenFileDialog control has the following basic attributes:

InitialDirectory Initial directory of the dialog box
Filter File filter to be displayed in the dialog box, for example, "text file (*. txt) | *. txt | all files (*. *) | *.*"
FilterIndex The index of the file filter selected in the dialog box. If the first item is selected, it is set to 1.
RestoreDirectory Whether to restore the current directory before closing the control dialog box
FileName The first file displayed in the dialog box or the last selected file
Title Characters displayed in the title bar of the dialog box
AddExtension Whether to automatically add the default Extension
CheckPathExists Check whether the specified path exists before returning in the dialog box.
DefaultExt Default Extension
DereferenceLinks Whether to cancel the reference shortcut before returning from the dialog box
ShowHelp Enable the "help" button
ValiDateNames The control dialog box checks whether invalid characters or sequences are not included in the file name.

2. The OpenFileDialog control has the following common events:

FileOk The event to be processed when you click "open" or "save ".
HelpRequest Event to be processed when the user clicks the "help" button

3. OpenFileDialog:

You can use the following code to implement the preceding dialog box:

Private void openFileDialogBTN_Click (object sender, System. EventArgs e ){
OpenFileDialog openFileDialog = new OpenFileDialog ();
OpenFileDialog. InitialDirectory = "c :\\"; // note that c: \ instead of c: \ is used to write the path here :\
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 ("");
}
}

The File () class is used to execute File operations in the program. I wrote it myself and attached the source code of this class. If you are interested, you can analyze it by yourself.

  Ii. Save file dialog box (SaveFileDialog)

The control of the Save file dialog box can be saved in two situations: save, save as, and save as easily. When the file is opened, write an article about the file, here we mainly talk about saving as (SaveAs ).

1. properties of the SaveFileDialog Control

Filter File filter to be displayed in the dialog box, for example, "text file (*. txt) | *. txt | all files (*. *) | *.*"
FilterIndex The index of the file filter selected in the dialog box. If the first item is selected, it is set to 1.
RestoreDirectory Whether to restore the current directory before closing the control dialog box
AddExtension Whether to automatically add the default Extension
CheckFileExists  
CheckPathExists Check whether the specified path exists before returning in the dialog box.
Container Determines whether a user is prompted when a file is to be created. This parameter is applicable only when ValidateNames is a true value.
DefaultExt Default Extension
DereferenceLinks Whether to cancel the reference shortcut before returning from the dialog box
FileName The first file displayed in the dialog box or the last selected file
InitialDirector Initial directory of the dialog box
OverwritePrompt Control whether to prompt the user when the current file is to be rewritten. It is applicable only when ValidateNames is true.
ShowHelp Enable the "help" button
Title Characters displayed in the title bar of the dialog box
ValidateNames The control dialog box checks whether invalid characters or sequences are not included in the file name.

2. The SaveFileDialog event is as follows:

FileOk The event to be processed when you click "open" or "save ".
HelpRequest Event to be processed when the user clicks the "help" button

3. The effect of SaveFileDialog is as follows:

4. Use the following sample code to implement

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: // The saved file has a name.
FSaveAs. WriteFile (richTextBox1.Text );
}
}
}

In fact, this can be done directly in the VS. net ide environment. To illustrate the problem, I still have a column. A File class library is used. The following is the source code:

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, "An error occurred while saving the file! ");}
}
}
}

FontDialog)

In text processing, we often use fonts. Now let's make the most common font dialog box.

  I. Common FontDialog attributes

ShowColor Controls whether to display color options
AllowScriptChange Whether to display the font Character Set
Font Font displayed in the dialog box
AllowVerticalFonts Whether vertical font can be selected
Color Color selected in the dialog box
FontMustExist Whether to display an error when the Font does not exist
MaxSize Optional maximum font size
MinSize Optional minimum font size
ScriptsOnly Display exclude OEM and Symbol Fonts
ShowApply Whether to display the "application" button
ShowEffects Whether to display underline, strikethrough, font color options
ShowHelp Whether to display the "help" button

  2. FontDialog event

Apply Event to be processed when you click "application ".
HelpRequest Event to be processed when the "help" button is clicked

  3. FontDialog

  IV. Implementation 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 Font of the selected text.
}
}

The above Code sets the selected text to the font in the current FontDialog dialog box.

  Color dialog box (ColorDialog)

The color pick-up box is also one of our common dialogs. Let's take a look at how the color dialog box is operated in C?

I. Common Properties of the color dialog box (ColorDialog)

AllowFullOpen Disable and enable the "custom color" button
FullOpen Whether to display the "custom color" section of the dialog box first
ShowHelp Whether to display the "help" button
Color Color displayed in the dialog box
AnyColor Show any colors available
CustomColors Whether to display custom colors
SolidColorOnly Can only select solid color?

2. ColorDialog:

III. For the implementation code, see:

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 you click "cancel" in the ColorDialog dialog box
File: // restore the original value
ColorDialog. ShowDialog ();
RichTextBox1.SelectionColor = colorDialog. Color;
}

It is easy to implement the color dialog box (ColorDialog). In fact, it is not just a color dialog box, but C # is also very easy to learn. After finishing the ColorDialog dialog box, let's talk about Printing and page settings.

PageSetupDialog)

In fact, there is not much to talk about page settings (PageSetupDialog). Now, I will list the common attributes in PageSetupDialog.

  1. common attributes of PageSetupDialog

 

AllowMargins Set whether to edit the margin.
AllowOrientation Can I use "direction" single region?
AllowPaper Set whether to edit the paper size.
AllowPrinter Set whether the "Printer" button can be used
Document Obtain the PrintDocument set for the printer
MinMargins Minimum margin that can be selected

  2. The effect of PageSetupDialog is as follows:

That's easy. Let's take a look at the following. What about the more important stuff? About printing.

  Print pre-renewal and Printing

Printing is a feature that we often use in windows programming. It used to be very difficult to work, but in Microsoft. the printing in the net Framework is provided to us by components, but it is still a little troublesome, so it is specially written for your reference.

1. In the. net environment, when it comes to Printing, the PrintDocumet class cannot be mentioned. PrintDocument belongs to the namespace System. Drawing. Printing. The PrintDocument class is the core code for Printing.

To implement printing, you must first construct a PrintDocument object to add a printing event,
PrintDocument. PrintPage + = new PrintPageEventHandler (this. printDocument_PrintPage)
Printing actually calls the Graphics class method for drawing. The following code is rewritten according to the routine provided on MSDN. MSDN print routine address:

Http://msdn.microsoft.com/library/default.asp? Url =/library/en-us/cpref/html/frlrfsystemdrawingwintingprintdocumentclasstopic. asp. If you are interested, change it.

The following is the printDocument_PrintPage I have rewritten:

Private void printDocument_PrintPage (object sender, System. Drawing. Printing. PrintPageEventArgs e)
{
Float linesPerPage = 0; // The row number of the page
Float yPos = 0; // print the vertical position of the string
Int count = 0; // The row counter.
Float leftMargin = e. MarginBounds. Left; // Left margin
Float topMargin = e. MarginBounds. Top; // Top margin
String line = null; // a line string
Color clr = richTextBox1.SelectionColor; // The current print Color. Different colors are not printed in my program.
SolidBrush B = new SolidBrush (clr); // brush
Fnt = richTextBox1.SelectionFont; // current print font
LinesPerPage = e. MarginBounds. Height/fnt. GetHeight (e. Graphics); // Number of printable lines per page
File: // print one page row by row
While (count {
YPos = topMargin + (count * fnt. GetHeight (e. Graphics ));
E. Graphics. DrawString (line, fnt, B, leftMargin, yPos, new StringFormat ());
Count ++;
}
File: // If the page is printed and the line is not empty, the next printing event is triggered,
File: // in the next print, lineReader will automatically read the last unprinted content. LineReader can record the currently read location
If (line! = Null)
E. HasMorePages = true;
Else
E. HasMorePages = false;
}

The entire print task can be completed here. After constructing printDocument_PrintPage, you can print and print the pre-release.

 Ii. Print the Pre-Export Dialog Box (PrintPreviewDialog)

The print prepaster control is used to display the effect of a printed document after printing. The print pre-release dialog box contains buttons such as print, zoom, single page or multi-page, and close. The dialog box is as follows:

The print prefill dialog box does not have many attributes and is called by ShowDialog. The above implementation code is 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;
}
}

It's easy to write PrintDocument_PrintPage.

  3. Print the dialog box (PrintDialog)

1. The PrintDialog dialog box has the following attributes:

AllowPrintToFile Disable or use the "print to file" check box
AllowSelection Disable or use the "selected content" ticket
AllowSomePages Disable or use the "page" radio button
Document Obtain the PrintDocument set by the printer.
PrintToFile Whether to select the print to file check box
ShowHelp Control whether the "help" button is displayed
ShowNetWork Control whether the "network" button is displayed

2. The effect is as follows:

3. Use the following code:

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 (ex. Message );
}
}
}

At this point, all the dialogs are finished, and the headers are big.

The preceding dialog box can be completed in the IDE environment of vs.net. In this case, to illustrate the problem, we will separate it step by step.

  Summary

In our tutorial, the file dialog box (FileDialog), FontDialog, ColorDialog, PrintPreviewDialog, and PrintDialog are described) and the Print dialog box (PrintDialog). The file dialog box (FileDialog) includes the open file dialog box (OpenFileDialog) and save the file dialog box (SaveFi leDialog. With the above foundation, you can easily write a simple notebook.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.