WinForms Editor
WinForms Editor
Trademarks The ComponentOne product name is a trademark and ComponentOne is a registered trademark of ComponentOne LLC. All other trademarks used herein are the properties of their respective owners. Warranty ComponentOne warrants that the original CD (or diskettes) are free from defects in material and workmanship, assuming normal use, for a period of 90 days from the date of purchase. If a defect occurs during this time, you may return the defective CD (or disk) to ComponentOne, along with a dated proof of purchase, and ComponentOne will replace it at no charge. After 90 days, you can obtain a replacement for a defective CD (or disk) by sending it and a check for $25 (to cover postage and handling) to ComponentOne. Except for the express warranty of the original CD (or disks) set forth here, ComponentOne makes no other warranties, express or implied. Every attempt has been made to ensure that the information contained in this manual is correct as of the time it was written. We are not responsible for any errors or omissions. ComponentOnes liability is limited to the amount you paid for the product. ComponentOne is not liable for any special, consequential, or other damages for any reason. Copying and Distribution While you are welcome to make backup copies of the software for your own use and protection, you are not permitted to make copies for the use of anyone else. We put a lot of time and effort into creating this product, and we appreciate your support in seeing that it is used by licensed users only. This manual was produced using ComponentOne Doc-To-Help.
Table of Contents
ComponentOne Editor for WinForms Overview.......................................................................... 1 Installing Editor for WinForms.................................................................................................................1 Editor for WinForms Setup Files ..............................................................................................................1 System Requirements ...............................................................................................................................2 Installing Demonstration Versions ............................................................................................................2 Uninstalling Editor for WinForms ............................................................................................................2 End-User License Agreement ...................................................................................................................2 Licensing FAQs .......................................................................................................................................2 What is Licensing? ...................................................................................................................................3 How does Licensing Work? ......................................................................................................................3 Common Scenarios ..................................................................................................................................4 Troubleshooting .......................................................................................................................................6 Technical Support ....................................................................................................................................7 Redistributable Files .................................................................................................................................8 About this Documentation .......................................................................................................................8 Namespaces .............................................................................................................................................8 Creating a .NET Project ...........................................................................................................................9 Adding the Editor for WinForms Components to a Project..................................................................... 10 Key Features...................................................................................................................... 11 Editor for WinForms Elements .............................................................................................. 15 C1Editor Overview................................................................................................................................. 15 C1Editor Modes ..................................................................................................................................... 16 C1EditorToolStripMain Overview.......................................................................................................... 17 C1EditorToolStripObjects Overview....................................................................................................... 18 C1EditorToolStripStyle Overview .......................................................................................................... 18 C1EditorToolStripTable Overview ......................................................................................................... 18 Editor for WinForms Quick Start ........................................................................................... 18 Step 1 of 4: Adding Editor for WinForms Components to the Form........................................................18 Step 2 of 4: Binding C1Editor to a Document .........................................................................................19 Step 3 of 4: Applying a Cascading Style Sheet.........................................................................................20 Step 4 of 4: Running the Project.............................................................................................................. 22 C1Editor Design-Time Support...............................................................................................22 Smart Tags ............................................................................................................................................. 22 Context Menus....................................................................................................................................... 22 C1Editor Run-Time Elements.................................................................................................23 C1Editor Dialog Boxes...........................................................................................................................23 Bookmark Properties Dialog Box ........................................................................................................... 23 Movie in Flash Format Properties Dialog Box ........................................................................................24 Find and Replace Dialog Box ................................................................................................................. 24 Formatting Dialog Box...........................................................................................................................25 Hyperlink Properties Dialog Box ............................................................................................................ 26 Picture Properties Dialog Box................................................................................................................. 27 Page Setup Dialog Box ...........................................................................................................................28 Table Properties Dialog Box ...................................................................................................................29 Using a Custom Dialog Box ...................................................................................................................33 Keyboard Shortcuts ................................................................................................................................34 Creating an XHTML Editor in Code ........................................................................................35
iii
The ToolStripBase class..........................................................................................................................35 The ToolStripMain class.........................................................................................................................35 File Commands ...................................................................................................................................... 35 Clipboard Commands ............................................................................................................................37 Editing Commands ................................................................................................................................37 Word Count command...........................................................................................................................38 Spell-Checking Commands.....................................................................................................................40 Enabling and Disabling Commands........................................................................................................ 40 The ToolStripStyles class ........................................................................................................................41 Cascading Style Sheets ...........................................................................................................................41 Showing and Applying Styles ................................................................................................................. 43 Bold, Italic, Underline, Clear Formatting................................................................................................44 Enabling and Disabling Commands........................................................................................................ 45 Performing Other Common Tasks .......................................................................................................... 46 Selecting a Paragraph using the Select Method .......................................................................................47 Selecting a Paragraph using the XmlDocument ......................................................................................47 Search and Replace with the Selection object ..........................................................................................48 Search and Replace with the XmlDocument ...........................................................................................49 Editor for WinForms Samples.................................................................................................50 Editor for WinForms Task-Based Help .................................................................................... 51 Changing the C1Editor Mode................................................................................................................. 51 Binding C1Editor to a Document ........................................................................................................... 52 Loading an XHTML Document from a File ...........................................................................................52 Linking a ToolStrip to C1Editor ............................................................................................................. 53 Creating a Custom ToolStrip ..................................................................................................................53 Selecting Characters in the C1Editor....................................................................................................... 54 Using a Cascading Style Sheet with C1Editor .........................................................................................55
iv
To get started, review the following topics: - Key Features (page 11) - Quick Start (page 18) - Samples (page 50)
C1Editor
System Requirements
System requirements include the following: Operating Systems: Windows 2000 Windows Server 2003 Windows Server 2008 Windows XP SP2 Windows Vista Windows 7 Environments: .NET Framework 2.0 or later C# .NET Visual Basic .NET Disc Drive: CD or DVD-ROM drive if installing from CD
Licensing FAQs
This section describes the main technical aspects of licensing. It may help the user to understand and resolve licensing problems he may experience when using ComponentOne .NET and ASP.NET products.
What is Licensing?
Licensing is a mechanism used to protect intellectual property by ensuring that users are authorized to use software products. Licensing is not only used to prevent illegal distribution of software products. Many software vendors, including ComponentOne, use licensing to allow potential users to test products before they decide to purchase them. Without licensing, this type of distribution would not be practical for the vendor or convenient for the user. Vendors would either have to distribute evaluation software with limited functionality, or shift the burden of managing software licenses to customers, who could easily forget that the software being used is an evaluation version and has not been purchased.
These files are automatically added to the project. In WinForms and ASP.NET 1.x applications, the run-time license is stored as an embedded resource in the assembly hosting the component or control by Visual Studio. In ASP.NET 2.x applications, the run-time license may also be stored as an embedded resource in the App_Licenses.dll assembly, which is used to store all run-time licenses for all components directly hosted by WebForms in the application. Thus, the App_licenses.dll must always be deployed with the application. The licenses.licx file is a simple text file that contains strong names and version information for each of the licensed components used in the application. Whenever Visual Studio is called upon to rebuild the application resources, this file is read and used as a list of components to query for run-time licenses to be embedded in the appropriate assembly resource. Note that editing or adding an appropriate line to this file can force Visual Studio to add run-time licenses of other controls as well. Note that the licenses.licx file is usually not shown in the Solution Explorer; it appears if you press the Show All Files button in the Solution Explorer's Toolbox, or from Visual Studio's main menu, select Show All Files on the Project menu. Later, when the component is created at run time, it obtains the run-time license from the appropriate assembly resource that was created at design time and can decide whether to simply accept the run-time license, to throw an exception and fail altogether, or to display some information reminding the user that the software has not been licensed. All ComponentOne products are designed to display licensing information if the product is not licensed. None will throw licensing exceptions and prevent applications from running.
Common Scenarios
The following topics describe some of the licensing scenarios you may encounter.
In these cases, create a temporary Windows Forms application and add all the desired licensed components to a form. Then close the Windows Forms application and copy the licenses.licx file into the console application project. Make sure the licenses.licx file is configured as an embedded resource. To do this, right-click the licenses.licx file in the Solution Explorer window and select Properties. In the property window, set the Build Action property to Embedded Resource.
6.
Troubleshooting
We try very hard to make the licensing mechanism as unobtrusive as possible, but problems may occur for a number of reasons. Below is a description of the most common problems and their solutions.
I have a licensed version of a ComponentOne product but I still get the splash screen when I run my project.
If this happens, there may be a problem with the licenses.licx file in the project. It either doesn't exist, contains wrong information, or is not configured correctly. First, try a full rebuild (Rebuild All from the Visual Studio Build menu). This will usually rebuild the correct licensing resources. If that fails follow these steps: 1. 2. 3. 4. Open the project and go to the Solution Explorer window. Click the Show All Files button on the top of the window. Find the licenses.licx file and open it. If prompted, continue to open the file. Change the version number of each component to the appropriate value. If the component does not appear in the file, obtain the appropriate data from another licenses.licx file or follow the alternate procedure following. Save the file, then close the licenses.licx tab. Rebuild the project using the Rebuild All option (not just Rebuild). Open the project and go to the Solution Explorer window. Click the Show All Files button on the top of the window. Find the licenses.licx file and delete it. Close the project and reopen it. Open the main form and add an instance of each licensed control. Check the Solution Explorer window, there should be a licenses.licx file there. Rebuild the project using the Rebuild All option (not just Rebuild). Open the project and go to the Solution Explorer window. Find the licenses.licx file and right-click it. Select the Rebuild Licenses option (this will rebuild the App_Licenses.licx file). Rebuild the project using the Rebuild All option (not just Rebuild).
5. 6. 1. 2. 3. 4. 5. 6. 7. 1. 2. 3. 4.
I have a licensed version of a ComponentOne product on my Web server but the components still behave as unlicensed.
There is no need to install any licenses on machines used as servers and not used for development. The components must be licensed on the development machine, therefore the licensing information will be saved into the executable (.exe or .dll) when the project is built. After that, the application can be deployed on any machine, including Web servers.
For ASP.NET 2.x applications, be sure that the App_Licenses.dll assembly created during development of the application is deployed to the bin application bin directory on the Web server. If your ASP.NET application uses WinForms user controls with constituent licensed controls, the runtime license is embedded in the WinForms user control assembly. In this case, you must be sure to rebuild and update the user control whenever the licensed embedded controls are updated.
I downloaded a new build of a component that I have purchased, and now I'm getting the splash screen when I build my projects.
Make sure that the serial number is still valid. If you licensed the component over a year ago, your subscription may have expired. In this case, you have two options: Option 1 Renew your subscription to get a new serial number. If you choose this option, you will receive a new serial number that you can use to license the new components (from the installation utility or directly from the About Box). The new subscription will entitle you to a full year of upgrades and to download the latest maintenance builds directly from http://prerelease.componentone.com/. Option 2 Continue to use the components you have. Subscriptions expire, products do not. You can continue to use the components you received or downloaded while your subscription was valid.
Technical Support
ComponentOne offers various support options. For a complete list and a description of each, visit the ComponentOne Web site at http://www.componentone.com/Support. Some methods for obtaining technical support include: Online Support via HelpCentral ComponentOne HelpCentral provides customers with a comprehensive set of technical resources in the form of FAQs, samples, Version Release History, Articles, searchable Knowledge Base, searchable Online Help and more. We recommend this as the first place to look for answers to your technical questions. Online Support via our Incident Submission Form This online support service provides you with direct access to our Technical Support staff via an online incident submission form. When you submit an incident, you'll immediately receive a response via e-mail confirming that you've successfully created an incident. This email will provide you with an Issue Reference ID and will provide you with a set of possible answers to your question from our Knowledgebase. You will receive a response from one of the ComponentOne staff members via e-mail in 2 business days or less. Peer-to-Peer Product Forums and Newsgroups ComponentOne peer-to-peer product forums and newsgroups are available to exchange information, tips, and techniques regarding ComponentOne products. ComponentOne sponsors these areas as a forum for users to share information. While ComponentOne does not provide direct support in the forums and newsgroups, we periodically monitor them to ensure accuracy of information and provide comments when appropriate. Please note that a ComponentOne User Account is required to participate in the ComponentOne Product Forums. Installation Issues Registered users can obtain help with problems installing ComponentOne products. Contact technical support by using the online incident submission form or by phone (412.681.4738). Please note that this does not include issues related to distributing a product to end-users in an application. Documentation ComponentOne documentation is installed with each of our products and is also available online at
HelpCentral. If you have suggestions on how we can improve our documentation, please email the Documentation team. Please note that e-mail sent to the Documentation team is for documentation feedback only. Technical Support and Sales issues should be sent directly to their respective departments. Note: You must create a ComponentOne Account and register your product with a valid serial number to obtain support using some of the above methods.
Redistributable Files
ComponentOne Editor for WinForms is developed and published by ComponentOne LLC. You may use it to develop applications in conjunction with Microsoft Visual Studio or any other programming environment that enables the user to use and integrate the control(s). You may also distribute, free of royalties, the following Redistributable Files with any such application you develop to the extent that they are used separately on a single CPU on the client/workstation side of the network: C1.Win.Editor.2.dll Site licenses are available for groups of multiple developers. Please contact [email protected] for details.
Namespaces
Namespaces organize the objects defined in an assembly. Assemblies can contain multiple namespaces, which can in turn contain other namespaces. Namespaces prevent ambiguity and simplify references when using large groups of objects such as class libraries. The namespace for the C1Editor component is C1.Win.C1Editor. The following code fragment shows how to declare a C1Editor component using the fully qualified name for this class: Visual Basic Dim Editor1 As C1.Win.C1Editor.C1Editor C#
C1.Win.C1Editor.C1Editor Editor1; Namespaces address a problem sometimes known as namespace pollution, in which the developer of a class library is hampered by the use of similar names in another library. These conflicts with existing components are sometimes called name collisions. For example, if you create a new class named C1Editor, you can use it inside your project without qualification. However, the C1Editor assembly also implements a class called C1Editor. So, if you want to use the C1Editor class in the same project, you must use a fully qualified reference to make the reference unique. If the reference is not unique, Visual Studio .NET produces an error stating that the name is ambiguous. The following code snippet demonstrates how to declare these objects: Visual Basic ' Define a new C1Editor object Dim MyEditor as C1Editor ' Define a new C1Editor.C1Editor object. Dim C1Editor as C1.Win.C1Editor.C1Editor C# // Define a new C1Editor object C1Editor MyEditor; // Define a new C1Editor.C1Editor object. C1.Win.Editor.C1Editor C1Editor;
Fully qualified names are object references that are prefixed with the name of the namespace where the object is defined. You can use objects defined in other projects if you create a reference to the class (by choosing Add Reference from the Project menu) and then use the fully qualified name for the object in your code. Fully qualified names prevent naming conflicts because the compiler can always determine which object is being used. However, the names themselves can get long and cumbersome. To get around this, you can use the Imports statement (using in C#) to define an alias an abbreviated name you can use in place of a fully qualified name. For example, the following code snippet creates aliases for two fully qualified names, and uses these aliases to define two objects: Visual Basic Imports C1Editor = C1.Win.C1Editor Imports MyEditor = MyProject.C1Editor Dim s1 As C1Editor Dim s2 As MyEditor C# using C1Editor = C1.Win.C1Editor; using MyEditor = MyProject.C1C1Editor; C1Editor s1; MyEditor s2; If you use the Imports statement without an alias, you can use all the names in that namespace without qualification, provided they are unique to the project.
3. 4.
Select Windows Application from the list of Templates in the right pane. Enter or browse for a location for your application in the Location field and click OK. A new Microsoft Visual Studio .NET project is created in the specified location. In addition, a new Form1 is displayed in the Designer view. Double-click the C1Editor component from the Toolbox to add it to Form1. For information on adding a component to the Toolbox, see Adding the Editor for WinForms Components to a Project (page 10).
5.
To use these controls, add them to the form or add a reference to the C1.Win.C1Editor assembly to your project. Adding Editor for WinForms Controls to the Toolbox To add Editor for WinForms controls to the Visual Studio Toolbox: 1. 2. 3. 4. Open the Visual Studio IDE (Microsoft Development Environment). Make sure the Toolbox is visible (select Toolbox in the View menu if necessary) and right-click it to open the context menu. To make the Editor for WinForms components appear on its own tab in the Toolbox, select Add Tab from the context menu and type in the tab name, C1Editor, for example. Right-click the tab where the component is to appear and select Choose Items from the context menu. The Choose Toolbox Items dialog box opens. In the dialog box, select the .NET Framework Components tab. Sort the list by Namespace (click the Namespace column header) and check the check boxes for the component belonging to namespace C1.Win.C1Editor. Note that there may be more than one component for each namespace.
Adding Editor for WinForms Controls to the Form To add Editor for WinForms controls to a form: 1. 2. Add Editor for WinForms controls to the Visual Studio Toolbox. Double-click a control or drag it onto your form.
Adding a Reference to the C1.Win.C1Editor Assembly To add a reference to the assembly: 1. Select the Add Reference option from the Project menu of your project.
10
2. 3.
Select the ComponentOne C1Editor assembly from the list on the .NET tab or browse to find the C1.Win.C1Editor.2.dll file and click OK. Double-click the form caption area to open the code window. At the top of the file, add the following Imports statements (using in C#): Imports C1.Win.C1Editor
Note: This makes the objects defined in the C1.Win.C1Editor assembly visible to the project. See Namespaces (page 8) for more information.
Key Features
The following are some of the main features of C1Editor that you may find useful: "On the fly" synchronizing with XmlDocument Bind the C1Editor control to a document specified in the Document property. If the document is edited within the C1Editor, the underlying XmlDocument syncs to match it. If the XmlDocument changes in code, these changes are visible in the C1Editor control at run time. See Binding C1Editor to a Document (page 52) for more information. C1Editor provides three edit modes: Design, Source, and Preview The C1Editor control features three editor modes: Design, Source, and Preview. You can determine which of these views users will see initially by setting the Mode property. See the C1Editor Overview (page 15) for more information. Load and save Xhtml documents from or to a file or stream You can load an XHTML document into C1Editor from a file, stream or XML string. You can save an XHTML document to a file or stream. See the Editor for WinForms Task-Based Help (page 51) for examples on how to do this. Editor for WinForms offers Cascading Style Sheet support, including easy-to-define custom CSS styles for Design and Preview mode C1Editor fully supports cascading style sheets (CSS) in edited documents. In addition, you can specify external CSS rules in CSS files which will be used only in Design or Preview mode. The LoadDesignCSS and LoadPreviewCSS methods support this feature by loading a cascading style sheet from a file or stream. See Using a Cascading Style Sheet with C1Editor (page 55) for an example on using the LoadDesignCSS method. Code clean-up routines On document loading, switching off Source mode, or on executing the ValidateSource or FixSource methods, C1Editor automatically removes empty tags, closes unclosed tags, and generally improves messy or unreadable HTML or XHTML code, converting it to valid XHTML. Editor for WinForms' built-in spell checker allows you to check as you type Spell-checking functionality is provided by ComponentOne's C1SpellChecker component. C1Editor fully supports C1SpellChecker so you can use all of its great features, including: modal Dialog mode (users can choose to correct or ignore errors through a dialog box), As-you-type mode (spelling errors are indicated by a red, wavy underline), and the AutoReplace feature (misspelled words are
11
automatically corrected as you type). In As-you-type mode, the built-in C1Editor context menu merges with the C1SpellChecker context menu so you can see and select all available commands. Ability to add custom tags in DTD Advanced programming tasks sometimes require using additional DTD elements in the edited document. You can enter the elements, or tags, in the document specifying them using the XmlExtensions property in special XML format. See the CustomTags sample installed with this product for a complete example of this feature. Access and manage data from code selections and the caret position You can access content in the C1Editor by specifying a range of characters to select. For an example, see Selecting Characters in the C1Editor (page 54). Text decoration and block formatting commands You can easily set font and text decoration and block formatting properties in a text block without worrying about how to modify the underlying XmlDocument. Use the C1TextRange class to identify target text and the C1TextRange methods to apply the decoration or formatting: ApplyTag, ApplyClass, ApplyStyle, and ApplyFormatting. Use built-in or custom dialog boxes to insert links, pictures, tables, and other objects You can show built-in or custom dialog boxes to insert or edit various objects at the current selection. The dialog boxes allow you to specify all properties of the inserted or edited object. For example, the Picture dialog box contains fields to select the image source, or file name, alternate text, size, and so on. C1Editor also has a built-in Find and Replace dialog box that allows the user to specify a string to search for and a replacement string, as well as the options to use when searching for text in a document. If you prefer, you can create and use your own find and replace dialog box, specifying it in the CustomDialogs property of the C1Editor. For more information on C1Editor's built-in dialog boxes, or for steps on how to use your own, see C1Editor Dialog Boxes (page 23). Use the mouse to move or resize pictures or tables You can interact with objects directly in Design mode by specifying their size or position with the mouse. Moving is a direct manipulation. You can move an object within a document in any direction. C1Editor will move relative to the XmlNode and/or set the new position attributes of the object automatically. Resizing allows you to resize the selected object in the direction of the mouse pointer movement. C1Editor will set the new size attributes of the object automatically. Printing support Calling the Print method has the same effect as choosing Print from the Windows Internet Explorer File menu. The Print method can activate the Print dialog box, prompting the user to change print settings. The PrintPreview method lets you see the Web page before you print it so you can avoid printing mistakes. See the PrintTemplate sample installed with this product for a complete example of this feature. Clipboard support You can select text, tables or graphics and use the Cut or Copy methods of C1Editor to move your selection to the Clipboard. Then you can paste the selection into another program. You can copy HTML from a program or even a picture in Internet Explorer and then use the Paste method to put it into the C1Editor. The PasteAsText method automatically formats the text you paste into the C1Editor as plain text.
12
C1Editor also supports keyboard shortcuts such as CTRL+C (copy), CTRL+X (cut), and CTRL+V (paste). To determine what clipboard operations are allowed, use the CanCut, CanCopy, CanPaste, and CanPasteAsText properties. History of changes (undo/redo) C1Editor has an unlimited undo history mechanism. You can programmatically access the editing history, calling the Undo or Redo methods. The Undo and Redo methods also support keyboard shortcuts: CTRL+Z (undo) and CTRL+Y (redo). By undoing repeatedly, a user can gradually work back to the point before the error was made.
13
The C1EditorToolStrips can be added to your form and linked to the C1Editor control through the Editor property. See Linking a ToolStrip to C1Editor (page 53) for more information. You also have the option of implementing your own ToolStrip using the C1EditorToolStripBase as the base class. You can then add an C1EditorToolStripButton or C1EditorToolStripComboBox to a standard ToolStrip and set the Editor and Command properties. See Creating a Custom ToolStrip (page 53) for more information.
C1Editor Overview
The C1Editor control is a rich text editor that can be bound to an Xhtml document. Any document bound to the C1Editor control can be loaded, saved or edited.
Compared to the RichTextBox that ships with Visual Studio, the C1Editor has the following advantages: 4. C1Editor uses XHTML as its basic format (instead of RTF or proprietary formats). XHTML is a specialized version of XML, which means it is extremely easy to automate all kinds of document handling tasks. C1Editor fully supports cascading style sheets that separate content from presentation and facilitate document handling even further. You can choose to edit documents in preview or source mode, editing the XML tags directly or seeing the document as it will appear to the final users. C1Editor has a powerful and simple object model based on the XmlDocument class. If you manipulate XML documents using the XmlDocument class, you already know how to create and edit documents programmatically with the C1Editor.
5.
6.
15
7.
C1Editor supports advanced features such as tables, lists, images, and as-you-type spell-checking. This is the same editor we use in our own award-winning Doc-To-Help documentation tool. (Spell-checking is based on the C1SpellChecker component which works great with the C1Editor). C1Editor ships with four specialized ToolStrip controls that allow you to build complete user interfaces without writing any code. Add the toolstrip to the form, connect it to a C1Editor by setting the toolstrip's Editor property, and you have a professional quality XHTML editor.
8.
C1Editor Modes
The C1Editor control features three editor modes: Design, Source, and Preview. You can determine which of these views users will see initially by setting the Mode property. Design View This view displays the text editor's content in a What-You-See-Is-What-You-Get (WYSIWYG) format. Here you can add content without markup. The following image shows the C1Editor in Design view:
Source View This view provides a hand-coding environment for writing and editing HTML markup. The following image shows the text editor in Source view:
16
Preview View In this mode, no editing is allowed; Preview mode is strictly for viewing the content. The following image shows the text editor in Preview mode:
You can set the initial run-time view of the text editor by setting the Mode property. The EditorMode enumeration can be set to one of three settings: Design, Source, or Preview. For more information on how to set the editing mode, see Changing the C1Editor Mode (page 51). Scrollbars will automatically appear if content added to the text editor exceeds the available screen space.
C1EditorToolStripMain Overview
The C1EditorToolStripMain control is a standard text-style ToolStrip made up of C1EditorToolStripButtons allowing you to: create, open, save or print a new file; cut, copy, and paste text; undo or redo an action; select all text or find and replace text; switch between design and source view; or preview the Xml document.
17
C1EditorToolStripObjects Overview
The C1EditorToolStripObjects control is made up of C1EditorToolStripButtons allowing you to insert objects, including tables, pictures, hyperlinks, bookmarks, and flash movies.
C1EditorToolStripStyle Overview
The C1EditorToolStripStyle control is made up of a C1EditorToolStripComboBox and C1EditorToolStripButtons allowing you to: set paragraph or heading styles, create bulleted or numbered lists; bold, italic, underline, or strikethrough your text; clear formatting; create subscript or superscript text; change the font size; or change paragraph alignment.
C1EditorToolStripTable Overview
The C1EditorToolStripTable control is made up of C1EditorToolStripButtons allowing you to: insert a table; set table, row, column, and cell properties; insert a row above or below the selected row; insert a column before or after the selected column; and delete a table, row, or column.
18
3.
Add one button to the form and arrange the controls so they look like the following image:
4. 5. 6.
Right-click the C1EditorToolStripMain control on your form and select Properties. In the Visual Studio Properties window, click the drop-down arrow next to the Editor property and select c1Editor1. This links the toolstrip to the C1Editor control. Select button1 and enter Apply CSS next to the Text property in the Properties window.
19
3.
Create a Form_Load event and add the following code there to create a new document and bind it to C1Editor: Visual Basic Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Dim myDoc As New XmlDocument() C1Editor1.Document = myDoc End Sub C# private void Form1_Load(object sender, EventArgs e) { XmlDocument myDoc = new XmlDocument(); c1Editor1.Document = myDoc; }
In the next step you will add code to apply a cascading style sheet to the C1Editor content.
20
h3 {
} h4 {
font-family: Verdana; font-size: 16pt; font-weight: bold; line-height: normal; margin-bottom: 7pt; margin-left: 0pt; margin-right: 0pt; margin-top: 9pt; page-break-after: avoid; font-family: Verdana; font-size: 12pt; font-weight: bold; line-height: normal; margin-bottom: 2pt; margin-left: 0pt; margin-right: 0pt; margin-top: 2pt; page-break-after: avoid;
} .C1HBullet { font-family: Verdana; font-size: 10pt; font-style: italic; line-height: 14pt; margin-bottom: 0pt; margin-left: 18pt; margin-right: 0pt; margin-top: 5pt; text-indent: -18pt; } p { font-family: Verdana; font-size: 10pt; line-height: 14pt; margin-bottom: 0pt; margin-left: 0pt; margin-right: 0pt; margin-top: 5pt; text-indent: 18pt; } .C1SectionCollapsed { font-weight: bold; } 4. 5. 6. 7.
Click the Save button and save the style sheet as myCSS.css, for example. Right-click the project name in the Solution Explorer and select Add | Existing Item. Choose the CSS and click Add. Create a Button1_Click event and add the following code there so the cascading style sheet is applied when the button is clicked. The location may be different, depending on where you save your Visual Studio project. Visual Basic Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
21
In the next step you will run the project and add text to the editor.
Congratulations! You have successfully completed the Editor for WinForms Quick Start.
Smart Tags
The Editor for WinForms controls include a smart tag ( ) in Visual Studio. A smart tag represents a shortcut tasks menu that provides the most commonly used properties in the controls. To access the Tasks menu, click the smart tag in the upper-right corner of the control. The Tasks menus is similar for all Editor for WinForms controls and it operates as follows: About C1Editor Displays the About ComponentOne Editor dialog box, which is helpful in finding the version number of the product and online resources such as how to purchase a license, how to contact ComponentOne, or how to view ComponentOne product forums.
Context Menus
The Editor for WinForms controls have additional commands available on their context menus that Visual Studio provides for all .NET and ASP.NET controls. Right-click anywhere on one of the controls to display the context menu. The context menu commands operate as follows: About C1Editor
22
Displays the About ComponentOne Editor dialog box, which is helpful in finding the version number of the product and online resources such as how to purchase a license, how to contact ComponentOne, or view ComponentOne product forums.
23
Click the Browse button to locate a Flash movie. Enter the text that should appear in case the movie is unavailable.
Select this checkbox and enter a number to specify the movie window width. Choose pixels or percent. Select this checkbox and enter a number to specify the movie window height. Choose pixels or percent.
Options Autoplay Loop Select this check box to automatically start the movie when the document is loaded. Select this check box to continuously play the movie.
24
To find specific text, enter the text in the Find what text box, select one of the check boxes under Find options, and click Find Next. To replace specific text, enter the text to be replaced in the Find what text box, enter the text to replace it in the Replace with text box, and click Replace to replace certain instances or click Replace All to replace all instances. Find Options The Find options section of the Find and Replace dialog box allows you to specify certain search criteria as described in the following table:
Option Match case Match whole word only Search up Description Locates text that exactly matches the combination of uppercase and lowercase letters you type in the Find what box. Locates distinct occurrences of words, not groups of characters inside words. Searches for text specified in the Find what box from the bottom of the control upwards.
25
Font properties Font family Size Text color Click the drop-down arrow next to Font family to select from the list of available font families. Enter a number to specify the text size. Click the drop-down arrow next to Text color to select from Web, System, or custom colors.
Effects Select the Bold, Italic, or Invisible check boxes to add the effect to the text. If Invisible is selected, the text will be hidden in Preview mode. Text decoration Select Overline, Strikeout, Underline, or None (default) to add decoration to the text.
26
Basic Text to display Address Advanced Screen tip Target frame Access key Tab index Enter the tooltip text that will appear when a user hovers over the hyperlink. Click the drop-down arrow to select a frame where the web page will appear when the hyperlink is clicked. Enter a key that can be pressed with the ALT key to jump to a specific control on the page without using the mouse. Enter a number to define the tab order for the hyperlink. Enter the text that will appear as a hyperlink in the document. Enter the URL address for the hyperlink.
27
Click the Browse button to locate a picture to insert. Enter the text that should appear in case the image is unavailable.
Select this checkbox and enter a number to specify the image width. Choose pixels or percent. Select this checkbox and enter a number to specify the image height. Choose pixels or percent.
28
Paper Options Page Size Portrait or Landscape Print Background Colors and Images Enable Shrink-to-Fit Margins Specify the page margins in the Left, Right, Top, and Bottom boxes. Headers and Footers Click the drop-down arrows under Header or Footer to select the header or footer to be inserted, or create your own custom header or footer. Click the Change Font button to change the header or footer font, style, and size. Click the drop-down arrow and select a paper size. Select Portrait or Landscape to determine the page orientation. Select this checkbox to print background colors and pictures. Select this checkbox to scale the content to fit on the page.
29
Enter the caption to appear above the table. Enter a description for the table.
Enter the number of table columns. Enter the number of table rows. Select this checkbox to specify the width of the table, either in percent or pixels.
Alignment Cell spacing Cell padding Enter a number to determine spacing between cells. Enter a number to determine the spacing that appears around cell content.
30
Row Properties
Right-click a table and select Row Properties to access this dialog box. Click the drop-down arrows next to Vertical or Horizontal to specify the alignment.
Column Properties
Right-click a table and select Column Properties to access this dialog box.
31
Alignment Vertical Horizontal Click the drop-down arrows to specify the vertical alignment: top, middle, or bottom. Click the drop-down arrows next to Horizontal to specify the alignment: left, center, or right.
Size Specify width Select this checkbox and enter a number in pixels or percent for the width of the column.
Span Column Enter a number to determine how many columns the property changes should affect.
Cell Properties
Right-click a table and select Cell Properties to access this dialog box.
32
Alignment Vertical Horizontal Click the drop-down arrows to specify the vertical alignment: top, middle, or bottom. Click the drop-down arrows next to Horizontal to specify the alignment: left, center, or right.
Span Column Row Enter a number to determine how many columns the property changes should affect. Enter a number to determine how many rows the property changes should affect.
Header Select this checkbox format the text in a cell as a header, or centered and bold.
33
editor.CustomDialogs.BookmarkDialog = new BookmarkEditorForm(); editor.CustomDialogs.FindReplaceDialog = new FindReplaceForm(); editor.CustomDialogs.FormattingDialog = new FormattingForm(); } Then you can use the ShowDialog method to open each new dialog box. In this example, we have a toolStrip with three buttons that, when clicked, open the custom dialog boxes. private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { // opens the Bookmark dialog box if (e.ClickedItem == buttonBookmark) editor.ShowDialog(C1.Win.Editor.DialogType.Bookmark); // opens the Find dialog box else if (e.ClickedItem == buttonFind) editor.ShowDialog(C1.Win.Editor.DialogType.Find); // opens the Formatting dialog box else if (e.ClickedItem == buttonFormatting) editor.ShowDialog(C1.Win.Editor.DialogType.Format); } For a detailed example on creating and using custom dialog boxes, see the Custom Dialogs sample installed with the product.
Keyboard Shortcuts
The Editor for WinForms controls allow users to complete several functions through the use of keyboard shortcuts when the KeyboardShortcutsEnabled property is set to True (default). The following table details the functions that can be accessed through keyboard shortcuts:
Function Bold Italicize Underline Undo Redo Select All Copy Cut Paste Clear Formatting Find Replace Keyboard Shortcut Ctrl+B Ctrl+I Ctrl+U Ctrl+Z Ctrl+Y Ctrl+A Ctrl+C, Ctrl+Shift+Insert Ctrl+X, Ctrl+Delete CTRL+V, Ctrl+Shift+Insert Ctrl+Space Ctrl+F Ctrl+H
34
File Commands
The ToolStripMain class implements the usual New, Open, Save and Save As file commands. The New command is implemented as follows: bool NewDocument() { if (OKToDiscardChanges()) { Editor.Document = new System.Xml.XmlDocument(); _fileName = null;
35
SetDirty(false); return true; } return false; } The method calls a helper OkToDiscardChanges method that checks whether the loaded document has any changes. If it does, the method prompts the user to verify that it is OK to discard the changes before creating a new document. To actually create the new document, the method sets the C1Editor's Document property to a new instance of an XmlDocument object. The XmlDocument represents the content of the editor, and you may use the XmlDocument object model to modify the document. This is one of the main strengths of the C1Editor control. It allows you to create and modify document content using the powerful and familiar XmlDocument object model. This will be demonstrated in more detail in later sections. The Open command is implemented as follows: bool LoadDocument() { if (OKToDiscardChanges()) { using (OpenFileDialog dlg = new OpenFileDialog()) { // get file name dlg.Filter = Properties.Resources.FileFilter; dlg.DefaultExt = Properties.Resources.DefaultExt; if (dlg.ShowDialog() == DialogResult.OK) { try { // load document Editor.LoadXml(dlg.FileName); _fileName = dlg.FileName; SetDirty(false); return true; } catch (Exception x) { MessageBox.Show(x.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } } } // canceled... return false;
As before, the method starts by calling the OKToDiscardChanges method. It then uses an OpenFileDialog to allow the user to pick the document he wants to load. Finally, the method calls the C1Editor's LoadXml method to load the document into the editor. The Save method is implemented in a similar way: bool SaveDocument()
36
// no name? go get one... if (string.IsNullOrEmpty(_fileName)) { return SaveDocumentAs(); } // got the name, save the file try { Editor.SaveXml(_fileName); SetDirty(false); return true; } catch (Exception x) { MessageBox.Show(x.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; }
The method starts by checking whether the current document already has a file name associated with it. If it does not, then it calls the SaveDocumentAs method, which prompts the user for a file name and then returns to the SaveDocument method. Once the document has a file name, the method uses the C1Editor's SaveXml method to save the current document to the file.
Clipboard Commands
The ToolStripMain class implements the usual Cut, Copy, and Paste clipboard commands. All clipboard commands are deferred to the C1Editor itself: void Cut_Click(object sender, EventArgs e) { Editor.Cut(); } void Copy_Click(object sender, EventArgs e) { Editor.Copy(); } void Paste_Click(object sender, EventArgs e) { Editor.PasteAsText(); //.Paste(); } The C1Editor clipboard commands are simple and easy to use, like the ones in the regular TextBox and RichTextBox controls. Notice that the Paste command is implemented with a call to the PasteAsText command. This ensures that the text being pasted is not interpreted as XHTML.
Editing Commands
The ToolStripMain class implements the usual Undo, Redo, Find, and Replace commands, which are also deferred to the C1Editor control: void Undo_Click(object sender, EventArgs e)
37
Editor.Undo(); } void Redo_Click(object sender, EventArgs e) { Editor.Redo(); } void Find_Click(object sender, EventArgs e) { Editor.ShowDialog(C1.Win.C1Editor.DialogType.Find); } void Replace_Click(object sender, EventArgs e) { Editor.ShowDialog(C1.Win.C1Editor.DialogType.Replace); } The find and replace commands are implemented with calls to the C1Editor's ShowDialog commands, which also supports several other commands defined by the DialogType enumeration and not used in this sample: NewTable: Inserts a new table. Image: Inserts or edits an image. FlashMovie: Inserts or edits a Flash movie. Hyperlink: Inserts or edits a hyperlink. Bookmark: Inserts or edits a bookmark. Find: Finds text in the document. Replace: Finds and replaces text in the document. Format: Applies formatting the current selection. PageSetup: Shows a page setup dialog.
38
// count non-space chars if (!char.IsWhiteSpace(c)) { nonSpaceChars++; } // count paragraphs if (c == '\n' || i == length - 1) { if (i == length - 1 || text[i + 1] != '\n') { paragraphs++; } } // count sentences if (c == '.' || c == '!' || c == '?' || i == length - 1) { if (i == length - 1 || char.IsWhiteSpace(text, i + 1)) { sentences++; } } // count words if (char.IsLetterOrDigit(c)) { if (i == length - 1 || !char.IsLetterOrDigit(text, i + 1)) { words++; } }
// show statistics string msg = string.Format( "Words: {0:n0}\r\n" + "Characters: {1:n0}\r\n" + "Non-Space Characters: {2:n0}\r\n" + "Sentences: {3:n0}\r\n" + "Paragraphs: {4:n0}\r\n" + "Average Word Length: {5:n1}\r\n" + "Average Sentence Length: {6:n1}\r\n" + "Average Paragraph Length: {7:n1}\r\n", words, chars, nonSpaceChars, sentences, paragraphs, words > 0 ? nonSpaceChars / (float)words : 0f, sentences > 0 ? nonSpaceChars / (float)sentences : 0f, paragraphs > 0 ? nonSpaceChars / (float)paragraphs : 0f); MessageBox.Show(msg, "Word Count");
The method starts by declaring variables to hold the statistics it will calculate. It then retrieves the document contents as plain text using the Text property, and scans that string counting characters, words, sentences, and paragraphs. Finally, it displays a message box with the statistics.
39
This sample shows that although the C1Editor supports the rich and powerful XmlDocument object model, you can easily bypass that and get directly to the actual text content when that is convenient. The Text property is similar to the Text property in the RichTextBox control.
Spell-Checking Commands
The C1Editor implements spell-checking with a SpellChecker property that allows you to connect it to a C1SpellChecker component. The C1SpellChecker is a separate, stand-alone component that can be used to spell-check many types of controls including TextBox, RichTextBox, WebBrowser, and of course the C1Editor. The C1SpellChecker includes spelling dictionaries for over 20 languages, and it includes a dictionary editor that allows you to create your own custom dictionaries. The C1Editor supports as-you-type spell checking (with red wavy lines under misspelled words and suggestions in context menus) as well as a dialog-based spell checking that highlights each misspelled word and allows the user to correct each one from the spell dialog. The ToolStripMain class exposes as-you-type spell-checking as follows: void ShowSpellingErrors_Click(object sender, EventArgs e) { if (SpellChecker != null) { bool show = !_btnShowErrors.Checked; _btnShowErrors.Checked = show; SpellChecker.SetActiveSpellChecking( Editor, Editor.GetActiveXInstance(), show); } } The core of the method is a call to the C1SpellChecker's SetActiveSpellChecking method, which turns the asyou-type spell checking on or off for the specified control. The ToolStripMain class exposes modal spell-checking as follows: void Spell_Click(object sender, EventArgs e) { if (SpellChecker != null) { SpellChecker.CheckControl( Editor, Editor.GetActiveXInstance()); } } The core of the method is a call to the C1SpellChecker's CheckControl method, which performs the dialogbased spell-checking for the specified control.
40
_btnPaste.Enabled = Editor.CanPasteAsText; // CanPaste _btnUndo.Enabled = Editor.CanUndo(); _btnRedo.Enabled = Editor.CanRedo(); _btnSpell.Enabled = _btnShowErrors.Enabled = SpellChecker != null; } The implementation is self-explanatory. The C1Editor provides properties and methods that allow the toolstrip to update itself very easily.
41
cmb.DropDownStyle = ComboBoxStyle.DropDownList; foreach (string name in _css.Keys) { cmb.Items.Add(name); } Items.Add(cmb); return cmb;
This code executes only once, when the tool strip is initialized. It creates a dictionary with four style sheets and adds their names to the combo box on the toolstrip. When one of the items in the combo box is selected, the following event handler applies the selected style sheet to the C1Editor: void _cmbCss_SelectedIndexChanged(object sender, EventArgs e) { var css = _css[_cmbCss.Text]; using (var s = new MemoryStream(Encoding.UTF8.GetBytes(css))) { Editor.LoadDesignCSS(s); } } The code retrieves the style sheet from the dictionary, then creates a stream from the style sheet string, and calls the LoadDesignCSS method to apply the style sheet to the document. The images below show the same document with different style sheets applied to it:
42
The ability to separate appearance from content by using style sheets is extremely important. Using this mechanism, you can update the appearance of entire document libraries by changing a single style sheet file. You can also create different style sheets for use when posting documents on web pages or print versions for example.
Next, three event handlers are used to apply the selected style when the user interacts with the combo box: void _cmbStyle_LostFocus(object sender, EventArgs e) { ValidateAndApplyStyle(); } void _cmbStyle_SelectedIndexChanged(object sender, EventArgs e)
43
ValidateAndApplyStyle(); } void _cmbStyle_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { ValidateAndApplyStyle(); } } All event handlers use the same ValidateAndApplyStyle method to actually apply the new style to the selection: void ValidateAndApplyStyle() { string style = _cmbStyle.Text; int start = style.IndexOf('<'); int end = style.IndexOf('>'); if (end > -1 && end > start) { var tag = style.Substring(start + 1, end - start - 1); Editor.Selection.ApplyTag(tag); } } The method starts by retrieving the tag from the combo box, and then applies the style to the current selection using the Selection object's ApplyTag method. In addition to the ApplyTag method, the Selection object also provides RemoveTag and IsTagApplied methods for managing the tags applied to the selection. Note that although these tags affect the appearance of the document, they are really related to the structure of the document. The actual appearance of a <p> or <h1> tag for example is defined by the style sheet that is currently applied to the document.
44
The first three commands use helper properties defined by the ToolStripStyles class: SelectionFontBold, SelectionFontItalic, and SelectionFontUnderline. These helper properties are implemented as follows: private bool SelectionFontBold { get { return Editor.Mode == EditorMode.Design ? Editor.Selection.IsTagApplied("strong") : false; } set { if (value) { Editor.Selection.ApplyTag("strong"); } else { Editor.Selection.RemoveTag("strong"); } } } The implementation uses the C1Editor's Selection property, which returns a Selection object that represents the current selection. The Selection object has methods to apply, remove, and check whether formatting tags are applied to the selection. The same logic used above is used to implement the SelectionFontItalic and SelectionFontUnderline helper properties.
45
// find selected style XmlNode node = GetSelectedNode(); if (node == null) { _cmbStyle.SelectedIndex = 0; } else { bool found = false; while (node != null && !found) { string style = string.Format("<{0}>", node.Name); foreach (string item in _cmbStyle.Items) { if (item.IndexOf(style) > -1) { _cmbStyle.Text = item; found = true; break; } } node = node.ParentNode; } }
The method starts by updating the state of the bold, italic, and underline buttons using the helper properties described earlier. Then it calls the GetSelectedNode to retrieve the XmlNode that represents the current selection and looks for the matching node type in the cmbStyle combo box. If a match is not found, parent nodes are scanned until a match is found or until we reach the top level node in the document. The GetSelectedNode method is implemented as follows: XmlNode GetSelectedNode() { // return node if start and end nodes are the same Selection selRange = Editor.Selection; if (selRange != null) { XmlNode startNode = selRange.Start.Node; XmlNode endNode = selRange.End.Node; return object.Equals(startNode, endNode) ? startNode : null; } return null; } The method starts by retrieving the Selection property, then checking that its start and end nodes are the same. If the selection spans multiple nodes, the method returns null which indicates there is no single style representing the selection.
46
This section focuses on other types of task that are commonly needed when implementing methods that process documents programmatically. Specifically, we will show you how to select and replace text in the document using the C1Editor's Selection object and using the XmlDocument object of the current document. Both tasks can be performed using either approach, which can be useful in different situations.
The code starts by retrieving the Text property and replacing cr/lf combinations with simple lf characters. This is necessary to get the selection indices to match the content of the document. Next, the code uses the IndexOf helper method to find the position of the sixth paragraph. Finally, it selects the paragraph using the Select method. The implementation of the IndexOf method is as follows: int IndexOf(string text, char chr, int count) { for (int index = 0; index < text.Length; index++) { if (text[index] == chr) { count--; if (count <= 0) { return index; } } } return text.Length; }
47
The code is considerably simpler. It retrieves the current document from the C1Editor, and then uses the SelectNodes helper method to get a list of all paragraph tags. It then creates a C1TextRange object, moves this new range to the node that represents the sixth paragraph in the document, and selects the range using the C1TextRange's Select method. The SelectNodes method is a handy utility that takes care of XML namespaces by automatically creating and using an XmlNamespaceManager (this is standard XmlDocument logic, not directly related to the C1Editor): XmlNodeList SelectNodes(XmlDocument doc, string xpath) { if (doc.DocumentElement.Attributes["xmlns"] != null) { // add namespace manager string xmlns = doc.DocumentElement.Attributes["xmlns"].Value; XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("x", xmlns); xpath = xpath.Replace("/", "/x:"); return doc.SelectNodes(xpath, nsmgr); } else { return doc.SelectNodes(xpath); } }
48
{ }
break;
// select match this.c1Editor1.Select(start, search.Length); // replace text and make it bold this.c1Editor1.Selection.Text = replace; this.c1Editor1.Selection.ApplyTag("strong");
// done MessageBox.Show(string.Format("Done, {0} instances found.", count)); } The code implements a loop that gets the editor's content as plain text and looks for a "search" string using the standard string.IndexOf method. When a match is found, the code selects the string using the Select method and then replaces the text by modifying the Text property of the Selection object. As a bonus, the code also makes the replacement bold by applying the "strong" tag to the replacement text. A good degree of compatibility with the familiar object model of the TextBox and RichTextBox classes is an important feature of the C1Editor.
49
The changes made to the XmlDocument are automatically reflected in the C1Editor. Exposing the power and flexibility of the XmlDocument object model for processing XHTML documents is one of the main advantages of the C1Editor control.
VB.NET Samples
Sample C1WordsX Description This sample shows how you can use the C1Editor control to build a rich text editor. The editor contains a Ribbon control and shows how you can implement formatting, search and replace, tables,
50
images, spell-checking, PDF export, and other advanced text editing features using the C1Editor control. CustomDialogs This sample demonstrates how to create custom dialogs for: - inserting/editing hyperlinks, bookmarks, picture, objects and tables; - implementing find/replace commands; - implementing basic text formatting. The C1Editor control contains built-in dialogs for all these tasks, but on some occasions you may want to implement your own in order to customize their appearance or behavior. CustomTags EditModes This sample shows how you can define and use your own custom tags. This sample shows how the Mode property works. The application contains a form with a C1Editor control. You can set the Mode property of the C1Editor using the buttons at the bottom of the form. PrintTemplate ToolStrips SyntaxHighlight UserCSS C1EditorQuickStart This sample demonstrates how you can customize the print and print preview features. This sample shows how you can use toolstrips from the C1.Win.Editor.ToolStrips namespace. This sample shows how to implement a syntax-highlighting editor using a C1Editor. This sample shows how you can customize the appearance of the document using custom CSS files. This sample shows how to implement a basic text editor application using the C1Editor control.
Add the following code to the Page_Load event to set the Mode property.
51
Note: Please note this sample changes the editor mode to Source. You can also set this property to Design or Preview. 4. Press F5 to build the project and observe C1Editor opens in Source view.
3.
Add the following code to the Page_Load event to set the Document property.
52
5.
Add the following code to the Page_Load event. This code uses the LoadXml method to load your XHTML document into the C1Editor. You will need to update the file path to the location of the XHTML document on your machine. Visual Basic C1Editor1.LoadXml("C:\galaxy.htm") C# c1Editor1.LoadXml(@"C:\galaxy.htm");
6.
Run the project and the C1Editor will show your XHTML document.
Note: If you expand the Editor property node, you can set other properties for the C1Editor here. Setting the Editor property Programmatically Add the following code to your form, in the Form_Load event, for example: Visual Basic C1EditorToolStripMain1.Editor = C1Editor1 C# c1EditorToolStripMain1.Editor = c1Editor1;
53
AddButton(C1.Win.C1Editor.ToolStrips.CommandButton.Cut); AddButton(C1.Win.C1Editor.ToolStrips.CommandButton.Copy); AddButton(C1.Win.C1Editor.ToolStrips.CommandButton.Paste); } } public class C1EditorToolStripButton : ToolStripButton { public C1Editor Editor { get; set; } public CommandButton Command { get; set; } } private void Form1_Load(object sender, EventArgs e) { // Using MyToolStrip in an application: MyToolStrip toolStrip = new MyToolStrip(); this.Controls.Add(toolStrip); toolStrip.Editor = c1Editor1; } } }
54
55
of the Baltimore Colts for 17 years)</p></li><li><p class="C1HBullet">Arnold Palmer (Golf legend and winner of more than 60 PGA events, including the Masters and the U.S. Open)</p></li></ul><p class="C1SectionCollapsed">Singers</p><ul><li><p class="C1HBullet">Perry Como (Recorded over 100 hit singles)</p></li><li><p class="C1HBullet">Bobby Vinton ("Roses are Red" and "Blue Velvet" hit #1 on the Billboard charts)</p></li></ul><p class="C1SectionCollapsed">Writers</p><ul><li><p class="C1HBullet">Rachel Carson (Author of "Silent Spring," as well as a pioneering environmentalist)</p></li></ul></body></html> 5. 6. Go back to your form and double-click it. In the Form_Load event, enter code to load the .xml document so it looks like the following: private void Form1_Load(object sender, EventArgs e) { c1Editor1.LoadXml(Resources.sEditorText, null); } Create a CSS and add it to your project by right-clicking the project name in the Solution Explorer, select Add Existing Item, choosing the CSS, and clicking Add. You can use this sample CSS if you don't already have one. html { font-family: Verdana; font-size: 10pt; line-height: normal; margin-bottom: 0pt; margin-left: 0pt; margin-right: 0pt; margin-top: 0pt; } h1 { font-family: Verdana; font-size: 20pt; font-weight: bold; line-height: normal; margin-bottom: 8pt; margin-left: 0pt; margin-right: 0pt; margin-top: 10pt;
Load a CSS 1.
} h2 {
font-family: Verdana; font-size: 16pt; font-weight: bold; line-height: normal; margin-bottom: 7pt; margin-left: 0pt; margin-right: 0pt; margin-top: 9pt; page-break-after: avoid;
56
} h3 { font-family: Verdana; font-size: 16pt; font-weight: bold; line-height: normal; margin-bottom: 7pt; margin-left: 0pt; margin-right: 0pt; margin-top: 9pt; page-break-after: avoid;
} h4 { font-family: Verdana; font-size: 12pt; font-weight: bold; line-height: normal; margin-bottom: 2pt; margin-left: 0pt; margin-right: 0pt; margin-top: 2pt; page-break-after: avoid;
} .C1HBullet { font-family: Verdana; font-size: 10pt; font-style: italic; line-height: 14pt; margin-bottom: 0pt; margin-left: 18pt; margin-right: 0pt; margin-top: 5pt; text-indent: -18pt; } p { font-family: Verdana; font-size: 10pt; line-height: 14pt; margin-bottom: 0pt; margin-left: 0pt; margin-right: 0pt; margin-top: 5pt; text-indent: 18pt; } .C1SectionCollapsed { font-weight: bold; } 2. Add a button1_Click event and use the LoadDesignCSS method: private void button1_Click(object sender, EventArgs e) { c1Editor1.LoadDesignCSS(@"C:\CSS1.css");
57
} Run the Project 1. 2. Press F5 to run the project. Notice the document is loaded in the C1Editor. Click the button. The document is formatted with the CSS.
For a detailed example of using custom cascading style sheets, see the UserCSS sample that comes with this product.
58