• No results found

Informatics LAB 6 Simple Text Editor

N/A
N/A
Protected

Academic year: 2020

Share "Informatics LAB 6 Simple Text Editor"

Copied!
10
0
0

Loading.... (view fulltext now)

Full text

(1)

INFORMATICS

LABORATORY WORK #6

Simple Text Editor

(2)

Simple Text Editor

We will be creating a simple text editor that allows you to format the text, save, and open an existing file. This lesson uses the ToolStrip and RichTextBox controls as its main components. Start by creating a new Windows Forms Application and name it

SimpleTextEditor. Drag a ToolStrip control from the Toolbox to the form. We will use the standard items for our tool bar so click the square button to the upper right edge of the ToolStrip and choose Insert Standard Items.

(3)

Add a separator and three new ToolStripButtons to the ToolStrip. Name the buttons boldToolStripButton, italicToolStripButton, and

underlineToolStripButton. The images that they will be using can be viewed. After you have downloaded and extracted the icons, assign each icon to their corresponding ToolStripButton using their Image property. If the files are hidden when you are browsing them, be sure that you use All Files as the file type. After you set the images for the three buttons, your form should now look like this:

Let’s add another item in to the ToolStrip that will determine the font to be used by the editor. Add another separator and a ToolStripComboBox control. Increase the width of your form so the new item will not overflow. Name the combo box

fontsToolStripComboBox. Your form should now look like this:

(4)

One way to resize a ToolStrip item is by setting its AutoSize property to False. You also need to set the AutoSize property of the ToolStrip itself to False. Finally, set the Size property to 50, 23 to make the width smaller and look more like the one seen in word processors. Using its Items property, provide several font sizes that the user can choose from (5, 8, 10, 12, 14, 16, 18, 20, 24, 30, 45, 72). You form should look like this:

Finally for our user interface, we need to add a RichTextBox control where the actual text will be displayed and typed. Drag a RichTextBox control from the toolbox to the form and change its Dock property to Fill. Name the control

editorRichTextBox. Our final user interface looks like the following:

(5)

We will now start the coding process for our Simple Text Editor. We will start at the first button which is the New Button. Double click that button and use the following event handler for its Click event.

private void newToolStripButton_Click(object sender, EventArgs e) {

editorRichTextBox.Clear(); }

The code simply clears the content of the RichTextBox editor.

The next button allows us to open an existing file. We will limit the user to only openning text and RTF files. Double click the button and use the following event handler.

1: private void openToolStripButton_Click(object sender, EventArgs e) 2: {

3: OpenFileDialog openDialog = new OpenFileDialog(); 4: openDialog.InitialDirectory = @"C:\";

5: openDialog.Multiselect = false; 6: openDialog.DefaultExt = "txt";

7: openDialog.Filter = "Text Files|*.txt|RTF|*.rtf"; 8:

9: DialogResult result = openDialog.ShowDialog(); 10:

11: if (result == DialogResult.OK) 12: {

13: string extension = System.IO.Path.GetExtension(openDialog.FileName); 14:

15: if (extension == ".txt")

16: editorRichTextBox.LoadFile(openDialog.FileName, 17: RichTextBoxStreamType.PlainText);

18: else

19: editorRichTextBox.LoadFile(openDialog.FileName, 20: RichTextBoxStreamType.RichText);

21: } 22: }

When you click the Open button, an OpenFileDialog will show up. Lines 3-7 are involve in creating and initializing the properties for the OpenFileDialog. Line 7 specifies that the user can only open .txt and .rtf files using the

OpenFileDialog.Filter property. Line 9 opens the dialog using the ShowDialog()

method. The user will choose the file to open. If the user presses the Open button of the dialog, then ShowDialog() will return DialogResult.OK. We test this in line 11, and if so, we first retrieve the extension in line 13 to determine what kind of file to show. We used the System.IO.Path.GetExtention() method and pass the filename of the selected file to extract the extention of it. If the extention is for a plain text file (.txt), then we used the LoadFile() method of the RichTextBox and pass

RichTextBoxStreamType.PlainText as the second parameter to indicate that the

RichTextBox should treat the contents of the file as a plain text.

Otherwise, we used the RichTextBoxStreamType.RichText to indicate that the RichTextBox should read and render the RTF codes within the file being openned.

(6)

private void saveToolStripButton_Click(object sender, EventArgs e) {

SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.InitialDirectory = @"C:\";

saveDialog.DefaultExt = "txt";

saveDialog.Filter = "Text Files|*.txt|RTF|*.rtf";

DialogResult result = saveDialog.ShowDialog();

if (result == DialogResult.OK) {

string extension = Path.GetExtension(saveDialog.FileName);

if (extension == ".txt")

editorRichTextBox.SaveFile(saveDialog.FileName, RichTextBoxStreamType.PlainText); else editorRichTextBox.SaveFile(saveDialog.FileName, RichTextBoxStreamType.RichText); } }

The next buttons are used for cutting, copying, and pasting texts. Use the following event handlers for them.

private void cutToolStripButton_Click(object sender, EventArgs e) {

editorRichTextBox.Cut(); }

private void copyToolStripButton_Click(object sender, EventArgs e) {

editorRichTextBox.Copy(); }

private void pasteToolStripButton_Click(object sender, EventArgs e) {

editorRichTextBox.Paste(); }

We simply used the methods provided by the RichTextBox control for cutting, copying, and pasting texts.

The next button allows the selected text in the editor to be bold. Double click the

Bold button and use the following for its event handler.

1: private void boldToolStripButton_Click(object sender, EventArgs e) 2: {

3: try 4: {

5: editorRichTextBox.SelectionFont = new Font(editorRichTextBox.SelectionFont, 6: editorRichTextBox.SelectionFont.Style ^ FontStyle.Bold);

7: } 8: catch 9: {

10: editorRichTextBox.SelectionFont = new Font(fontsToolStripComboBox.SelectedText,

11: Single.Parse(sizeToolStripComboBox.Text), FontStyle.Bold); 12: }

(7)

Let’s look at lines 5-6. We used the SelectionFont property of the

RichTextBox control to modify the font style. We used the contructor for the Font to assign a new modified font. The first parameter passes an existing font (so it will preserve the size, font family, etc.). The second parameter is the font style. We used the XOR (^) operator to add or remove the Bold font style to the current font style of the selected font.

A problem occurs when you are selecting text containing multiple fonts. For example, if you select the text Hello World and Hello uses Times New Roman, and World

uses Arial, then SelectionFont won’t be able to choose which to use from the two and it will contain null as the value. That’s why we enclosed Lines 5-6 in a try block to test for

NullReferenceException. If that error is encountered, then we simply assigned the selection with multiple fonts with whatever is in the font combo box and size combo box (we converted it to float). We simply applied the Bold style to the new font.

The code for the Italic and Underline buttons are quite similar. You simply change the FontStyle to add or remove in the parameter of the constructor.

private void italicToolStripButton_Click(object sender, EventArgs e) {

try {

editorRichTextBox.SelectionFont = new Font(editorRichTextBox.SelectionFont, editorRichTextBox.SelectionFont.Style ^ FontStyle.Italic);

} catch {

editorRichTextBox.SelectionFont = new Font(fontsToolStripComboBox.SelectedText, Single.Parse(sizeToolStripComboBox.Text), FontStyle.Italic);

} }

private void underlineToolStripButton_Click(object sender, EventArgs e) {

try {

editorRichTextBox.SelectionFont = new Font(editorRichTextBox.SelectionFont, editorRichTextBox.SelectionFont.Style ^ FontStyle.Underline);

} catch {

editorRichTextBox.SelectionFont = new Font(fontsToolStripComboBox.SelectedText, Single.Parse(sizeToolStripComboBox.Text), FontStyle.Underline);

} }

The next step is to load all the installed fonts to the fontToolStripComboBox. Double click the title bar of the form to generate an event handler to its Load event. Use the following event handler.

private void Form1_Load(object sender, EventArgs e) {

System.Drawing.Text.InstalledFontCollection fonts =

new System.Drawing.Text.InstalledFontCollection();

foreach (FontFamily family in fonts.Families) {

(8)

fontsToolStripComboBox.Text = editorRichTextBox.Font.FontFamily.Name; sizeToolStripComboBox.Text = editorRichTextBox.Font.Size.ToString(); }

The InstalledFontCollection class contains a collection of all the fonts currently installed into your system. We used a foreach loop to retrieve each

FontFamily object from the Families property of the

InstalledFontCollection class. We then add the names of each FontFamily

using its Name property. The two final lines detects the default font family and size of the editor and shows them in their respective tool strip combo boxes.

There is one problem left. If you run the program, select some text, and proceed to either the fontToolStripComboBox or sizeToolStripComboBox, the selection of the text in the editor is gone. To fix this, one way I did is to save the SelectionStart

and SelectionLength of the selection when the user leaves the editor, and when he/she returns to the editor, the text position and length specified by the

SelectionStart and SelectionLength is reselected. Add the following private fields inside the Form1 class.

private int selectionStart = 0; private int selectionLength = 0;

We then need to add an event handler for the RichTextBox‘s Leave event so proceed to the Designer, going to the Events section of the Properties Window, and finding the Leave event. Double click it and use the following event handler.

private void editorRichTextBox_Leave(object sender, EventArgs e) {

selectionStart = editorRichTextBox.SelectionStart; selectionLength = editorRichTextBox.SelectionLength; }

This code saves the SelectionStart and the SelectionLength of the currently selected text of the editorRichTextBox. We now need to add codes to the

Enter event of the editorRichTextBox. Use the following event handler for its Enter event to restore the selection when the editorRichTextBox gains back the focus.

private void editorRichTextBox_Enter(object sender, EventArgs e) {

editorRichTextBox.Select(selectionStart, selectionLength); }

We now need to add the codes for changing the font family of the selected text. In the Designer, select the fontsToolStripComboBox and find the

SelectedIndexChanged event. Use the following event handler.

private void fontsToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) {

editorRichTextBox.Focus();

(9)

editorRichTextBox.SelectionFont = new Font( fontsToolStripComboBox.SelectedItem.ToString(), editorRichTextBox.SelectionFont.Size, editorRichTextBox.SelectionFont.Style); } catch {

editorRichTextBox.SelectionFont = new Font(fontsToolStripComboBox.Text, Single.Parse(sizeToolStripComboBox.Text), FontStyle.Regular);

} }

Notice that we called the Focus() method first to reselect the text first before we applied the new modified font using another constructor of the Font class. The first parameter is the FontFamily to be used by the font. We used the selected font family of the fontsToolStripComboBox. The other two arguments specify the size and font style of the font. We passed the current size and font style of the selected font to these parameters. Like we did with the Bold, Italic, and Underline buttons, if an error occurs due to the selection having two or more fonts, then in the catch block, we simply applied whatever is in the fonts combo box and the size combo box. We simply set the style to a

Regular.

The code for the sizeToolStripComboBox is similar. Double click it and use the following event handler.

private void sizeToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) {

editorRichTextBox.Focus();

try {

editorRichTextBox.SelectionFont = new Font( editorRichTextBox.SelectionFont.FontFamily, Single.Parse(sizeToolStripComboBox.SelectedItem.ToString()), editorRichTextBox.SelectionFont.Style); } catch {

editorRichTextBox.SelectionFont = new Font(fontsToolStripComboBox.Text, Single.Parse(sizeToolStripComboBox.Text), FontStyle.Regular);

} }

Since we are changing the font of the selected text, the second parameter is based on the selected item of the sizeToolStripMenuComboBox. We then convert it to float using the Single.Parse() method. We also provide a catch block incase the user is selects a text which uses multiple font families.

(10)

References

Related documents

After phone interviews were conducted with parents or guardians, providers were mailed a questionnaire to acquire provider- con firmed immunization information for receipt of 3 doses

using Markdown to write our manuscript, we can use a simple text editor, and the

Open the your_domain_name.csr file in a text editor and copy the text, including the BEGIN and END tags.. Open the Deep Security for Web Apps console and click Protection

Click Save , which puts the file into the directory introtutorial and leads to the Text Editor window shown in Figure 16.. Maximize the

Compared to regular sparse grids, already our standard strategy for adaptive refinement significantly reduces the number of grid points which are required to obtain a certain

Another merit for MSA is the automatic satisfaction with the important property of wavelets, i.e.admissibility criteria, without which the bias in computing wavelet coefficients will

However, because the primary sources did not include records of individual reactions to the movie theaters, my hypothesis that Bloomington-Normal theaters were an escape,

To insert a link on a keyword expression that leads from one of your site’s pages to another, you have two options: Insert links with a rich text editor (simple) or with a plain