Browse by Tags
All Tags » Custom Controls (RSS)
-
|
See the DesignModeDialog sample. This sample is a component, much like the common dialogs, that has a ShowDialog method. When invoked, ShowDialog takes a snapshot of the parent form, clones all the controls and creates a new designer form with the controls...
|
-
|
The new DesignSurface class drastically simplifies the code necessary to host a designer in your own application. The following lines of code show the most simple designer that can be created. Note: to run this code, a reference to System.Design.dll will...
|
-
|
Override the InitializeNewComponent method on the ComponentDesigner attached to your control. This method is run the first time a control or component is added to the design surface. The corresponding InitializeExistingComponent is called when a control...
|
-
|
To provide a custom snapline for your control you need to override the SnapLines property on ControlDesigner. The CustomSnapline project shows how to add a text baseline snapline to a UserControl with a Label on it.
|
-
|
A snapline is a dynamically generated UI layout guide line. Snaplines are generated during control move operations in the designer. The location of other controls on the design surface provide the lines.
|
-
|
Items in categories with the same name will be grouped together on the smart tag panel. Items from different DesignerActionLists but with the same category as other items will be grouped together but will be separated by a line. To see an example of merging...
|
-
|
To show any dialog based UITypeEditor from a smart tag link, you'll need to provide an implementation of the ITypeDescriptorContext and IWindowsFormsEditorService interfaces. The EditorServiceContext class in the CustomDataGridViewSmartTag project...
|
-
|
As with all changes made to a Component or Control on the design surface, you'll need to raise ComponentChanged and ComponentChanging events. The easiest way to do this is to use PropertyDescriptor to set values. To see an example of using PropertyDescriptor...
|
-
|
If you cannot extend a control's designer you can push in a new DesignerActionList for a control using the DesignerActionSerivce. The CustomDataGridViewSmartTag project shows an example of this. The common use of this method is to use a global service...
|
-
|
The DesignerActionUIService can be used to refresh, hide and show the smart tag panel for any control or component. The SmartTagButton class in the SmartTagSample project shows an example use of the DesignerActionService.
|
-
|
There are two ways to do it. The most common is to override the DesignerActionListCollection property on the ComponentDesigner attached to your control. The SmartTagSample project shows this method. The other way is to get a hold of the DesignerActionService...
|
-
|
DesignerActionTextItem Represents a string on the smart tag panel DesignerActionHeaderItem Represents a bolded string on the smart tag panel DesignerActionMethodItem Represents a command link on the smart tag panel. Each method...
|
-
|
A smart tag is a new UI widget attached to a control or component's selection UI that provides easy access common actions and properties. A good way to think of a smart tag item is a DesignerVerbs on steroids. The API for smart tags can be found in...
|
-
|
The following HatchStyleEditor class draws a graphical representation for values in the HatchStyle enumeration. HatchStyleEditor is derived from UITypeEditor and ovverides the GetPaintValueSupported method and returns true. GetPaintValueSupported indicates...
|
-
|
Add a TypeConverter attribute to your class type to tell the Property Browser it should be expandable. [ TypeConverter( typeof( ExpandableObjectConverter ) ) ] public class MyClass { /* ... */ } Shawn Burke, Microsoft
|
-
|
You can do this but it's not as simple as using an attribute. If you want to modify the property names for your component, you have to interact with the reflection mechanism that the grid is using by implementing ICustomTypeDescriptor. The grid operates...
|
-
|
Use this custom editor attribute for the property that is of the StringCollection type (this can be used for other Collection types too if you want to allow entry of strings into the collection during design-time). Editor( "System.Windows.Forms.Design...
|
-
|
This is usually a problem if you have a custom collection type MyCollection which itself can take items of type MyCollection. This is a problem because a single instance of a UITypeEditor is used by the framework irrespective of how many types and instances...
|
-
|
The default CollectionEditor will allow the user to add objects of type returned by your collection's indexer method. You can make this CollectionEditor allow your user to pick the type of object to add by deriving from CollectionEditor and making...
|
-
|
The string "(Collection)" is coming from the TypeConverter on that property, which is CollectionConverter. You can modify the string as shown here: [ TypeConverter( typeof( CustomCollectionConverter ) ] public class CustomCollection : SomeBaseCollection...
|
-
|
You normally need this support when your control is parented by another custom Container Control that manages the location and size of your Control. You can prevent resizing by overriding this method in your custom ControlDesigner class: protected override...
|
-
|
You can subscribe to the SelectionChanged event in your control designer. using System.ComponentModel.Design; public class CustomContainerDesigner : ParentControlDesigner { private bool iamSelected; public override void Initialize( IComponent component...
|
-
|
Override OnPaintAdornments in your Control Designer. This will be called after the Control has painted. A good example is when you have a Control that has its border style set to None, and you want to draw a dummy border in the designer. protected override...
|
-
|
The design-time will forward the MouseEnter and MouseLeave messages to your control by default. The MouseMove message is blocked by the designer. You can get MouseDown and MouseUp messages in your control if you override GetHitTest method in your designer...
|
-
|
Override the DrawGrid property in the custom designer: public class CustomContainerDesigner : ParentControlDesigner { protected override bool DrawGrid { get { return disableDrawGrid ? false : base.DrawGrid; } } } Contributed from George Shepherd's...
|
-
|
To restrict your Container Control to parent only certain types of controls, override as follows in your designer: public class CustomContainerControlDesigner : ParentControlDesigner { public override bool CanParent( Control control ) { return control...
|
-
|
You have to store a reference to the DesignerVerb instance you create to represent the custom verb. You can then update the state of the verb through this reference. Here is an example: public class CustomControlDesigner : ParentControlDesigner { private...
|
-
|
You need to create custom "Verbs" for your Component or Control designer. This will make your verbs show up in the property browser and in the designer context menu. The designer generates an event when the user selects a verb, and you can handle...
|
-
|
You need to use a second instance of Visual Studio .NET to debug the one that's running the code. Put your control on a form in VS.NET. Start a second instance of VS.NET. Choose the Debug | Processes menu item. Double-click devenv.exe and choose Common...
|
-
|
Here are a couple of articles that discuss custom designers. Writing Custom Designers for .NET Components by Shawn Burke in the MSDN Library. .NET Shape Library: A Sample Designer by Brian Pepin on www.windowsforms.net . Contributed from George Shepherd's...
|
-
|
The CollectionEditor allows adding and removing items from a collection at design time. If the items in this collection implement IComponent or if they are derived from Component, the items in your collection can be persisted in code. Download collectioneditorsample...
|
-
|
Sometimes you might want to let the designer serializer serialize the changes in base fields via a property rather than the field itself using the AccessedThroughProperty attribute in the System.Runtime.CompilerServices namespace. public class CustomForm...
|
-
|
It is normal to have properties in your control or component whose default values are inherited from a base class control or component. In such cases you will normally prevent the designer from storing the property's value in code (using either DefaultValue...
|
-
|
You have to set DesignerSerializationVisibility attribute on the property whose type is a strongly-typed collection to Content. You have to ensure the collection is created at statup or on demand. In order to support serialization of items that do not...
|
-
|
You can do this by creating the editor yourself rather than allowing TypeDescriptor to do it as follows. First, shadow the property you care about in your designer: protected override void PreFilterProperties( IDictionaryProperties props ) { PropertyDescriptor...
|
-
|
Implement the ICustomTypeDescriptor interface on the control, and provide a PropertyDescriptor for the property that changes its return value for the IsReadOnly method. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
You can do this in different ways explained below. In all the cases the bitmap or icon should follow these rules: The bitmap or icon dimension should be 16x16 with 16 colors. The bottom-left pixel color will be assumed to be the transparent color. Technique...
|
-
|
Set this attribute for the property: [ RefreshProperties( RefreshProperties.Repaint ) ] Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Parse through all the Controls in the designer and call TypeDescriptor.Refresh() on them. From inside your custom IDesigner implementation: private void UpdateExtendedProperties() { IDesignerHost idh = GetService( typeof( IDesignerHost ) ) as IDesignerHost;...
|
-
|
Subscribe to IDesignerHost.LoadComplete event. Make any changes to the designer host (like adding or deleting components) only after this event, or else the design document will not be made "dirty". IDesignerSerializationManager.SerializationComplete...
|
-
|
Provide ShouldSerialize and Reset Methods along with your property. Example: private bool ShouldSerializeFont() { return this.bFontSet; } private void ResetFont() { this.localFont = null; } Contributed from George Shepherd's Windows Forms FAQ
|
-
|
For example, if you have a custom type: public class CustomSize { public int Width { get { /*...*/ } set { /*...*/ } } public int Height { get { /*...*/ } set { /*...*/ } } } And you want to the Width and Height properties to appear in that order, then...
|
-
|
If you have a custom data type like this: public class CustomSize { public int Width { get { /*...*/ } set { /*...*/ } } public int Height { get { /*...*/ } set { /*...*/ } } } Then write this: public class CustomSizeConverter : ExpandableObjectConverter...
|
-
|
You can provide IntelliSense support for your type and its members by providing XML comments in code as follows: using System.Windows.Forms; /// <summary> /// Summary description for CustomForm. /// </summary> public class CustomForm : Form...
|
-
|
You can use the menu selection Format | Move To Front or Format | Send To Back to change the z-order and update your docking. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Check the Form.DesignMode property. But note that when in Visual Inheritance mode (designing a derived form), your control's DesignMode property will be true when the base form's constructor gets executed in the design-time. To workaround this...
|
-
|
You have to implement a TypeConverter for your class and override the GetStandardValues and GetStandardValuesSupported method. In your override of GetStandardValuesSupported you have to return true. In your override of GetStandardValues you should return...
|
-
|
Type converters let you convert one type to another type. Each type that you declare can optionally have a TypeConverter associated with it using the TypeConverterAttribute. If you do not specify one the class will inherit a TypeConverter from its base...
|
-
|
Set the Designer attribute for your custom dialog to be ComponentDesigner (instead of the default ControlDesigner). That should make it droppable in the design surface as a component. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Provide the followoing attributes to your Property: [ Browsable( false ), EditorBrowsable( EditorBrowsableState.Always ) ] public bool CustomProperty{ get{} set{} } Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Use the MergableProperty attribute with a value of false. This will prevent your Property from being edited as part of a group in the designer. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
We have a small sample that shows how to do this. Download PropTab.zip . After you download and unzip the sample, build the project. Both the control assembly and a small driver assembly get built. After that add the control to your toolbox using 'Customise...
|
-
|
Set the Browsable attribute on the new property that hides the existing one. Here is a code snippet that hides the WordWrap property in the derived TextBox. [C#] public class CustomTextBox : TextBox { [ Browsable( false ) ] public new bool WordWrap {...
|
-
|
Use the DesignTimeVisible attribute set to false. [ DesignTimeVisible( false ) ] You can still provide a TypeConverter to make it participate in designer Serialization. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Use the ToolboxItem attribute set to false on your component or control class. This will prevent it from appearing in the Toolbox. [ ToolboxItem( false ) ] public class MyComponent : Component{..} Contributed from George Shepherd's Windows Forms FAQ
|
-
|
You could override WndProc and listen for (0x114 WM_HSCROLL) and (0x115 WM_VSCROLL) messages (m.Msg will be set to the above values). These messages should be sent when the user scrolls. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Windows Forms features a ScrollableControl. This will work in most cases where you know the exact dimensions of your control and scroll by pixel. See the MSDN Documentation for ScrollableControl for discussion how to use this control. Sometimes you may...
|
-
|
AutoScrollingMinSize is setup in device coordinates. If you are using a world coordinate system other than pixels this means that you have to translate between world and device coordinates before you set this value. You can use the Graphics.TransformPoints...
|
-
|
AutoScrolling, as provided by ScrollableControl.AutoScroll , does not allow you to dynamically control the scrolling interval. If you are drawing a complex control such as grid then you want to be able to scroll based on the current row height, column...
|
-
|
Change the control's Anchor property so that it is anchored on all four sides. Please note that you can only have one control per form anchored in this manner, i.e., on all four sides. And other controls on the form should be anchored by their sides...
|
-
|
G. G. Arun Ganesh discusses these properties in Working with Anchoring and Docking Properties on C# Corner .
|
-
|
By default, the arrow keys are not handled by a control's key processing code, but instead are filtered out for focus management. Hence, the control's KeyDown, KeyUp and KeyPressed events are not raised when you press an arrow key. If you want...
|
-
|
When you call the Focus method on a control, the control must be visible; otherwise focus will not be set. For example, if you call Focus on a control in Form_Load then focus will not be set. Instead consider setting the control's TabIndex property...
|
-
|
The .NET Framework Class Library does not provide a method to determine which control has keyboard focus, but you can invoke a Win32 API function to do this. Here's a custom form class that adds a GetFocusControl method to retrieve the .NET control...
|
-
|
I set a control's Visible property to true and in the next statement, it returns false. Why doesn't setting the Visible property work? A control's Visible property depends on its parent control's Visible property, if it has a parent control...
|
-
|
Override the control's WndProc method. This sample shows a custom control that is a ComboBox that discards the WM_KEYUP message. [C#] using System.Windows.Forms; public class ComboBoxWithNoKeyUp : ComboBox { private const int WM_KEYUP = 0x101; protected...
|
-
|
You should override the WndProc method in the control and process the WM_DISPLAYCHANGE message. You could also do this at the form level. For details on overriding the WndProc method, see How do I process Windows messages in a control? in this FAQ. Contributed...
|
-
|
You can handle the control's KeyPress event and indicate the key has been handled. Below is code that prevents a TextBox from getting an 'A' and the Enter key. private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs...
|
-
|
If the Control.ModifierKeys doesn't address your issue, then use P/Invoke and call GetKeyState directly. Declare this class first: [ ComVisibleAttribute( false ), SuppressUnmanagedCodeSecurityAttribute() ] internal class NativeMethods { [ DllImport...
|
-
|
Use the static property Control.ModifierKeys. Console.WriteLine(Control.ModifierKeys); if ( (Control.ModifierKeys & Keys.Shift) != 0 ) Console.WriteLine("the shift key is down"); if ( (Control.ModifierKeys & Keys.Alt) != 0 ) Console...
|
-
|
This can be done through the SendKeys class in the System.Windows.Forms namespace. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Say textBox1 and canelButton and the control names, then this is how you could do this: [C#] using System.ComponentModel; // Handler to the Validating event of the TextBox. private void TextBox_Validating( object sender, CancelEventArgs e ) { // Do this...
|
-
|
One way is to add code to your Validating handler and only execute the validation routine if the mouse is in the client area. This will avoid the click on the title bar and its system menu. You might also want to add special handling for the tab key so...
|
-
|
You can do so as follows in your Control: private void InvalidateWindow() { NativeMethods.RedrawWindow( Handle, IntPtr.Zero, IntPtr.Zero, 0x0400 | // RDW_FRAME 0x0100 | // RDW_UPDATENOW 0x0001 ); // RDW_INVALIDATE } Contributed from George Shepherd's...
|
-
|
You can do this in the DragDrop event handler of your control: [C#] using System.IO; try { // Use e.Data.GetData("UniformResourceLocator") to get the URL byte[] contents = new Byte[ 512 ]; Stream ioStream= (Stream) e.Data.GetData( "FileGroupDescriptor"...
|
-
|
You can set the control's Enabled property to false. This will prevent clicking but also gives the disabled look. There is a ControlStyles.Selectable flag that determines whether the control can get focus or not. But it does not appear to affect some...
|
-
|
Here is a method using Reflection to achieve this. [ DllImport( "user32.dll" ) ] private extern static int SendMessage( IntPtr hwnd, uint msg, int wParam, int lParam); object o = typeof( ToolTip ).InvokeMember( "Handle", BindingFlags...
|
-
|
Include a \n as part of the tiptext. toolTip1.SetToolTip( button1, "Press for\ninformation..." ); Contributed from George Shepherd's Windows Forms FAQ
|
-
|
From within the designer: 1) From the ToolBox, drap a ToolTip control to your form. 2) Check the properties of this toolTip1 object to make sure Active is set to true. 3) Click on your control (e.g., a button), and in its Property page, set the ToolTip...
|
-
|
One generic way for all controls is to get the difference between the ClientRectangle's width and the Control.Bounds' width. That should give the border width (and in general the non-client area width). Use the same approach for height. Contributed...
|
-
|
Override the custom control's CreateParams property as shown in this sample. protected override CreateParams CreateParams { get { CreateParams cparams = base.CreateParams; cparams.ExStyle &= ~512; cparams.Style &= ~8388608; // WS_BORDER cparams...
|
-
|
You will have to first provide some space in the NC area by setting the WS_BORDER flag in CreateParams and then draw the border yourself by listening to the WM_NCPAINT message in your Control, as follows: protected override CreateParams CreateParams ...
|
-
|
Providing a border in the non-client region of a control, rather than in the ClientRectangle, has several advantages. If you include a scrollbar in the control, the scrollbar will appear inside the border. If you draw the border in the client area, the...
|
-
|
Override the control's OnPaint method. Here is a sample custom Button. [C#] using System.Drawing; using System.Windows.Forms; public class ButtonWithCustomBorder : Button { protected override void OnPaint( PaintEventArgs e ) { base.OnPaint( e ); Color...
|
-
|
The (DynamicProperties) item that appears on the Properties window is used for setting property initialization through an XML file named app.config. Dynamic properties allow you to change property values without recompiling the application, for example...
|
-
|
To draw on any hwnd, you need to get a Graphics object from that hwnd. Once you have the Graphics object, you can then use its methods to draw. Of course, since this drawing is not done in the Paint handler, it will not be automatically refreshed when...
|
-
|
Handle the Paint event for your control or form. private void Form1_Paint( object sender, PaintEventArgs e ) { Graphics g = e.Graphics; Pen pen = new Pen( Color.White, 2 ); SolidBrush redBrush = new SolidBrush( Color.Red ); g.DrawEllipse( pen, 100, 150...
|
-
|
By default a control's background color will be the same as the container's background color. You can set the control's BackColor property to Transparent in the Designer. Select the control in the Designer, select the BackColor property in...
|
-
|
Make sure that you include the manifest file that will enable XP themes support for you application. Then the icons with alpha channel will draw semi-transparently. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Why do the XP Icons when drawn using Graphics.DrawImage not draw transparently? Note that it's only the ImageList class that can draw an Icon with alpha channel properly. So, instead of using the Graphics.DrawImage method, first associate this icon...
|
-
|
This is possible if the Control is drawn by the system, rather than by the framework. This is the case for example with the Label control when its set to FlatStyle.System. You should then set to to something else other than System for your transparent...
|
-
|
Sometimes the framework will throw an exception if you try to set the bg color to be transparent. This is because the Control doesn't support transparent colors. To work around this you should call this method from within the Control: SetStyle( ControlStyles...
|
-
|
The Window.Forms framework offers support for double buffering to avoid flickers through ControlStyles. Double buffering is a technique that attempts to reduce flicker by doing all the drawing operations on an off-screen canvas, and then exposing this...
|
-
|
Use the DrawImageDisabled method of the ControlPaint class. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
When custom initialization is to be done during runtime on certain controls, the best way is to implement the ISupportInitialize interface in that control. Then the BeginInit method will be called as soon as the control gets created, and EndInit will...
|
-
|
When I try to set a particular font style, say italics, I get an error message "Property cannot be assigned to -- it is read only". Code such as the following will not work . control.Font.Italic = true; Instead create a new Font object and set...
|
-
|
Use the Font property for the control along with the Font class in the System.Drawing namespace. button1.Font = new Font ( "Courier", 10, FontStyle.Bold ); Contributed from George Shepherd's Windows Forms FAQ
|
-
|
How do I programmatically change the color of a control? Set the control's BackColor and ForeColor properties. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
See Developing a Simple Windows Forms Control from .NET Framework Developer's Guide for a walk-through about creating Windows Forms custom controls. Tom Krueger, Microsoft
|
-
|
IDropTarget is a new interface that factors out the four drag drop methods - OnDragEnter, OnDragLeave, OnDragDrop, and OnDragOver - into an interface so that it can be implemented elsewhere. It is mostly an implementation detail.
|
-
|
I can't get the Windows Forms designer to notice changes to a nested component when the user sets properties on it through the property grid. I marked the property with the DesignerSerializationVisibility.Content attribute and all works perfectly...
|
-
|
I am trying to add custom snaplines to a UserControl, but I can't find any examples or documentation covering snaplines. A simple example: I would like to create a compound UserControl, containing two controls: Label1 and TextBox1. Then the Parenting...
|
-
|
I am having a problem with a custom control I created in Visual Studio 2005. After the control is added to a Form, the created Initializer code is incomplete and I have to finish it by hand. One of my properties is a class that implements IList. When...
|