Adding Context Sensibility to your own buttons

Once you added your own buttons or if you placed a toolsrtripButton on ToolStrip Control, you may want to change some properties of your custom button based on the context. For example, you may want the checked status to be TRUE for your custom Bold button, Italic Button, Underline Button etc if the selected or active context is bolded, italic or underlined etc.

First of all, let us explain how you can get Context Information :

You can get the context information anytime from the Composite Property StateQuery. This composite property has members for getting the context status of the editor . For example, the Bold button's checked status can be set by the following snippet.

toolStripButtonBold.Checked = htmlEditor1.StateQuery.IsBold();

In this way, you can check the status for Italic button, Underline button, Ordered List button, Unordered List Button etc. You may also check the active Font Family Name, Font Size, Font Color etc from this StateQuery object.


From the above screenshot, you can easily understand that, a lot of context information is available from this object. For example, you can see that there is a member named "IsImage()". Yes, that means, this member will return true if an image is selected or if an image is activated.

Now, let us explain, how can you detect the context changed and use this StateQuery to change your control's properties.

This control has an event named SelectionChanged. This SelectionChanged event is fired as soon as you change the caret from one element to another element. So, this event is the best place to host the logic for updating your control's properties based on context. For example, if you have 3 buttons in your Form named btnBold, btnItalic, btnUnderline who are responsible for applying bold, italic and underline formatting respectively. Now, the following snippet will show how to change properties of these buttons based on context changes.

1.Handle SelectionChanged event


2. Write Event Handler code as





3. Now, when you run the form, add some text and format some of the portion as Bold, and some of them as Underline. Now, keep changing your mouse caret and you will notice that the button's background colors are being changed based on the logic we just wrote here.


Last updated on Jun 27, 2012