Page 1 of 1

All you need to know about the button control A very in-depth guide to a very common control Rate Topic: ***-- 2 Votes

#1 RodgerB  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 66
  • View blog
  • Posts: 2,284
  • Joined: 21-September 07

Posted 21 December 2007 - 12:46 AM

All you need to know about the button control.

1) Introduction
Buttons in computing have been around since the Windows 1.1 era. Shaped rectangular with mildly rounded corners, the Button control has been a great success throughout Application Development, through to Web Development, primarily because it is easy to use, and users are often pressing them throughout the Windows Operating System.

The button control is your standard GUI function, usually used to confirm something or trigger an event. Such uses for a button include search engine's, dialog boxes, message boxes, etc. They are usually used to give the user an option or choice.

Here is an image of your average button:
Posted Image

Now that we know what a button is and it's purpose, we can start using it.

2) Properties

Here is a full list of the properties of the button control with information about their purpose and brief examples of it's usage.

2.01 - (ApplicationSettings)

The application settings property allows you to bind the control's properties to the configuration file's settings. To add applications settings do the following:

1) Open the properties window.
2) Expand the (ApplicationSettings) tree and select the (Property Binding) ellipsis button (...).
3) In this dialog, select a property to set a binding for.
4) In the drop-down list, select the (New...) to open another dialog.
5) Select a name for the setting and select a default value for the property.
6) Select a scope for the setting. The User scope means the settings will only be affective to the current user. The Application scope means for all users that use the application.
7) Now click OK for both dialogs.

By default the Text property will already be inside the tree, as VS thinks you are more likely to use it.

2.02 - (DataBindings)

The (DataBindings) property gets the binding objects for the button. The property takes advantage of the ControlBindingsCollection object. Databindings is a ReadOnly property.

2.03 - (Name)

The (Name) property refers to the name of the instance. Every control, class, form, pretty much anything you can think of has a name. When we originally place a Button on the form, it will call itself "Button" and append a number to the end of button. If we only have one button on the form, and it will default to Button1, however if we had a button already on the form, and this button was already named Button1, it would call the button Button2, and so on. The (Name) property is how we can access the control.

For example, say we kept the name of the control as Button1, and we added the following snippet to our code:

Button1.Text = "Hello World"

Hypothetically we wanted to rename our Button to ourNewName, we would need to change the code like so.

ourNewName.Text = "Hello World"

Fortunately, Visual Studio renames all these instances for us, so there is little time at all spent changing code around to suit a name change.

2.04 - AccessibleDescription

The AccessibleDescription property reports a description to those using accessibility clients. This property may be used to help a visually impared user / hearing / etc user to use your application.

The following quote would be sufficient to describe an exit button:


Click this button to exit the application.

Remember to give good descriptions when creating your controls for accessibility, if youare releasing it to the public etc, I'm sure you'd like to be able to use a computer without being scared away because you can't read properly. ;)

Example Code Usage:
Button1.AccessibleDescription = "Click this button to exit the application."

2.05 - AccessibleName

The AccessibleName property gives accessibility clients the name of the control. Something like Exit would be sufficient for an Exit Button.

Example Code Usage:
Button1.AccessibleName = "Exit"

2.06 - AccessibleRole

The AccessibleRole property reports the kind of role the object plays in accessibility. The field accesses the Windows.Forms.AccessibleRole enum to get the kind of type it is used for. In this case, we would probably like to use the PushButton member, as we are using a button.

Example Code Usage:
Button1.AccessibleRole = Windows.Forms.AccessibleRole.PushButton

2.07 - AllowDrop

The AllowDrop property is a boolean (true or false) value of whether dragging and dropping data onto the control is allowed or not. If allowed, you should use the DragDrop event assosiated with the control to accept the data.

Example Code Usage:
Button1.AllowDrop = True

2.08 - Anchor

The Anchor property will keep the button attached to the part of the container it is set to be. For example, if we put a button in a form, move it to the top right corner, set it's anchor to Top,Right, and change the size of the form, the control should stay in the top right corner.

Example Code Usage: (Use the Or operator to use both)
Button1.Anchor = (AnchorStyles.Top Or AnchorStyles.Right)

2.09 - AutoEllipsis

The AutoEllipsis property is a boolean value of whether the text should be handled if it extends beyond the width of the button. If it extends beyond the width of the box it will display three periods (the ellipsis charactor) appended to the end of the text, and when the control is resized it will automatically handle the text.

Unhandled Text ("I has unhandled text"):
Posted Image

Handled Text:
Posted Image

Example Code Usage
Button1.AutoEllipsis = True

2.10 - AutoSize

The AutoSize property will (if enabled) resize the button to fit it's contents, e.g. Text. I'm sure you have all seen a box resized to show all the contents so it would be kind of silly to make a comparison in this context.

Example Code Usage
Button1.AutoSize = True

2.11 - AutoSizeMode

The AutoSizeMode property will change the way AutoSize resizes the button. There are two options in the Windows.Forms.AutoSizeMode enum that gives us control, but that is all we really need.
  • Windows.Forms.AutoSizeMode.GrowAndShrink - Will make the control both grow and shrink when adjusting the size.
  • Windows.Forms.AutoSizeMode.GrowOnly - Will make the control grow to suit the contents but not shrink.

Example Code Usage
Button1.AutoSizeMode = Windows.Forms.AutoSizeMode.GrowOnly

2.12 - BackColor

The BackColor property controls the color of the button. This can be changed according to the value you provide. By default, you are given the 'Control' color. Because the BackColor property handles members of the Color Enum, we have a lot of options to choose from.

Posted Image Posted Image

Example Code Usage
Button1.BackColor = Color.Red

2.13 - BackgroundImage

The BackgroundImage property is rather self-explainitory; it displays an image for the background of a button. You can choose to get the image from your project files or a local resource. If you choose local resource, it will be imported into your project files regardless.

Example Code Usage
Button1.BackgroundImage = Image.FromFile("C:\afolder\anotherfolder\urImg.png")

2.14 - BackgroundImageLayout

The BackgroundImageLayout property will change the way the BackgroundImage displays. It works from the ImageLayout enumeration's members, so you have the following options:
  • ImageLayout.Center
  • ImageLayout.None
  • ImageLayout.Stretch
  • ImageLayout.Tile
  • ImageLayout.Zoom

Example Code Usage
Button1.BackgroundImageLayout = ImageLayout.Center

2.15 - CausesValidation

I have never heard or used this property before, but I decided I'd learn about it. Although I am not really qualified to teach anyone about as of yet, here is it's purpose:

Thanks to Exforsys Inc. - http://www.exforsys....validation.html


CausesValidation is one of the public instance properties of the control class, which specifies whether all controls which require validation gets it when the control gets focus. It returns true if the control causes validation to be performed on any controls requiring validation when it receives focus and false otherwise.

Validating event occurs when the control is validating at the time when the control loses the focus if the control’s CausesValidation property is true. Any code executed in response to this event can be used to throw exception if any is found. Validated Event occurs when the control has completed validation. This event occurs if no exception was thrown in the validating event. Clearing up the error provider messages can be done here.

Example Code Usage
Button1.CausesValidation = True

2.16 - ContextMenuStrip

The ContextMenuStrip property defines what information is displayed when the user right-clicks the button. You will need a ContextMenuStrip control to use this property.

Posted Image

Example Code Usage
Button1.ContextMenuStrip = cmsTehStrip

2.17 - Cursor

The Cursor property controls what type of cursor is displayed when the mouse is in the button. The property uses the Cursors enumeration's members to define the type of cursor displayed.

Example Code Usage
Button1.Cursor = Cursors.Arrow

2.18 - DialogResult

The DialogResult property is given a value when you'd like to give an indication of how the form got some information for a dialog. The DialogResult property uses the Windows.Forms.DialogResult enum's members to get a value.

Example Code Usage
Button1.Cursor = Cursors.Arrow

2.19 - Dock

The Dock property defines which borders of the control are stuck to the container. The Dock property takes advantage of the DockStyle enum's members.

Here is an example of a docked button, bound to the top of the container.
Posted Image

Example Code Usage
Button1.Dock = DockStyle.Top

2.20 - Enabled

The Enabled property indicates whether the control is enabled or disabled. When a button is disabled, it will:

a ) Not recieve any focus by any means.
b ) Not accept user-based events.
c ) Appear grayed-out.

Posted Image

Example Code Usage
Button1.Enabled = False

2.21 - FlatAppearance

If the FlatStyle property is set to FlatStyle.Flat, this property will be called upon to set the appearance. This property has 4 children:
  • BorderColor
  • BorderSize
  • MouseDownBackColor
  • MouseOverBackColor

Example Code Usage
With Button1.FlatAppearance
	.BorderColor = Color.Red
	.BorderSize = 2
	.MouseDownBackColor = Color.Blue
	.MouseOverBackColor = Color.LightSalmon
End With

2.22 - FlatStyle

The FlatStyle property determines the how the button appears; much like the BorderStyle property on the form. It has four options for you to choose from, all from the FlatStyle enum.

Example Code Usage
Button1.FlatStyle = FlatStyle.Flat

2.23 - Font

The Font property determines how the text should be displayed on the button. It contains 9 child properties:
  • Name
  • Size
  • Unit
  • Bold
  • GdiCharSet
  • GdiVerticalFont
  • Italic
  • Strikeout
  • Underline

Example Code Usage
Button1.Font = New Font("Times New Roman", 8.25, FontStyle.Regular, GraphicsUnit.Pixel)

2.24 - ForeColor

The ForeColor property controls the text color, and the shadow of the button. It uses the Color enumeration's members to get information as to which color should be displayed.

Posted Image

Example Code Usage
Button1.ForeColor = Color.Aqua

2.25 - GenerateMember

Another relatively undocumented property. Put very basically, the GenerateMember property is set to true if you want to use it's properties outside of InitializeComponent.

It is a design-time extender, so it can not be used programmatically.

2.26 - Image

The Image property gives the programmer the functionality of placing an image on the button. Much the same as the BackgroundImage property, except the Image property gives the ability of moving the image around, with the ImageAlign property.

Example Code Usage
Button1.Image = Image.FromFile("C:\afolder\anotherfolder\urImg.png")

2.27 - ImageAlign

The ImageAlign property is used to align the image specified in the Image property. ImageAlign handles members of the ContentAlignment enumeration.

Example Code Usage
Button1.ImageAlign = ContentAlignment.BottomCenter

2.28 - ImageIndex

The ImageIndex property is used to specify which image it is displaying in an ImageList. This property can only be used when a ImageList is present.

Example Code Usage
Button1.ImageIndex = 1

2.29 - ImageKey

The ImageKey property performs like the ImageIndex property, except the ImakeKey is the name of the image in the ImageList collection, for example, "tehImg.gif".

Example Code Usage
Button1.ImageKey = "tehImg.gif"

2.30 - ImageList

The ImageList property gives the programmer the functionality of using an ImageList control to set the image on the button.

Example Code Usage
Button1.ImageList = imlLol

2.31 - Location

The Location property is the X and Y value of the position on the form.

Example Code Usage
Button1.Location = New Point(50, 30)

2.32 - Locked

The Locked property is a design-time property that indicates whether the button can be moved around or resized, whilst designing your form. The control can not be used in code, primarily because there is no use.

2.33 - Margin

The Margin property defines the space between this button and another control. Although it doesn't prevent you from placing a control too close to the button, it sets a 'snap to' guide to aid placement.

As it is a design-time property, there is no need to assign a value to them, but however you can use Button1.Margin.Left etc, to get it's values.

2.34 - MaximumSize

The MaximumSize property is the maximum size the button can be at any given point. The property is controlled by the Size object to assign a new maximum size.

Example Code Usage
Button1.MaximumSize = New Size(50, 50)

2.35 - MinimumSize

Much the same as MaximumSize, the MinimumSize property is the minimum size the button can be at any given point. The property is controlled by the Size object to assign a new minimum size.

Example Code Usage
Button1.MinimumSize = New Size(30, 30)

2.36 - Modifiers

The Modifiers property indicates the visibility of the button (as far as programming with classes goes). By default, it is set to Friend. It can not be used programmatically.

2.37 - Padding

The padding property gives the programmer the ability to pad the inner contents inside the button. Padding generally refers to moving the contents a couple of pixels to the left or right, etc.

2.38 - RightToLeft

The RightToLeft property sets the text up to display RightToLeft. It's kinda useless with the button control because it's not going to make much difference. The RightToLeft property takes advantage of the Windows.Forms.RightToLeft enumeration.

Example Code Usage
Button1.RightToLeft = Windows.Forms.RightToLeft.Yes

2.39 - Size

The Size property indicates the size of the button control. It is formatted as an ordered pair (x,y). The Size property uses the Size() object to give it a value.

Example Code Usage
Button1.Size = New Size(320, 240)

2.40 - TabIndex

The TabIndex property indicates the order the button will gain focus when the user presses the TAB button on their keyboard, assuming Button1.TabStop = True.

Example Code Usage
Button1.TabIndex = 2

2.41 - TabStop

The TabStop property indicates whether the user can gain focus to the button by pressing tab. If set to False, it will skip the button when cycling through tabs.

Example Code Usage
Button1.TabStop = False

2.42 - Tag

The Tag property serves as a place for the programmer to store information. It's default value is nothing, and it belongs to the Object data type, hence the programmer can store practically any value.

Example Code Usage
Button1.Tag = "Ich mag die Zahlen laut!! :D"

2.43 - Text

The text property indicates the text which will be displayed on the button.

Posted Image

Example Code Usage
Button1.Text = "Exit"

2.44 - TextAlign

The TextAlign property indicates how the text is displayed on the Button. The property accepts members of the ContentAlignment enumeration.

Example Code Usage
Button1.TextAlign = ContentAlignment.BottomCenter

2.45 - TextImageRelation

The TextImageRelation property indicates how the text is wrapped with an image. For instance, you could want your image to be displayed over text. If this is the case you'd probably want to use this property. The TextImageRelation property ironically uses the TextImageRelation enumeration.

Example Code Usage
Button1.TextAlign = ContentAlignment.BottomCenter

2.46 - UseCompatibleTextRendering

Quote from MSDN (click):


Gets or sets a value that determines whether to use the compatible text rendering engine (GDI+) or not (GDI).

Example Code Usage
Button1.UseCompatibleTextRendering = False

2.47 - UseMnemonic

The UseMnemonic property indicates whether using the ampersand charactor in the text property will produce a hotkey, e.g. Button1.Text = "E&xit".

Example Code Usage
Button1.UseMnemonic = False

2.48 - UseVisualStyleBackColor

The UseVisualStyleBackColor property will set the background to use visual styles if it is supported.

Example Code Usage
Button1.UseVisualStyleBackColor = True

2.49 - UseWaitCursor

The UseWaitCursor property will set cursor to the Wait cursor until an operation has been completed, etc.

Example Code Usage
Button1.UseWaitCursor = True

2.50 - Visible

The Visible property indicates whether the button is visible or not.

Example Code Usage
Button1.Visible = True

3) Events

Events are lines of code that are triggered when an event occurs. An event could be:
  • A variable changed.
  • A mouse moved over the control
  • Etc. (I love that word).

Without any further ado, lets get straight into the nitty gritty of the event's the button control has to offer!
  • AutoSizeChanged - The AutoSizeChanged event will occur when the AutoSize property has been changed.
  • BackColorChanged - The BackColorChanged event will occur when the BackColor has been changed on the button.
  • BackgroundImageChanged - The BackgroundImageChanged event will occur when the BackgroundImage has been changed.
  • BackgroundImageLayoutChanged - The BackgroundImageLayoutChanged event will occur when the BackgroundImageLayout property has been changed.
  • BindingContextChanged - The BindingContextChanged event is called when the BindingContext property is changed.
  • CausesValidationchanged - The CausesValidationchanged event is called when the CausesValidation property is changed.
  • ChangeUICues - The ChangeUICues event occurs when the focus or keyboard UI cues change.
  • Click - The Click event occurs when the user clicks the button with the cursor.
  • ClientSizeChanged - The ClientSizeChanged event occurs when the ClientSize property is changed.
  • ContextMenuStripChanged - The ContextMenuStripChanged event occurs when the ContextMenuStrip property is changed.
  • ControlAdded - The ControlAdded event occurs when a control is added to the button.
  • ControlRemoved - The ControlRemoved event occurs when a control is removed from the button.
  • CursorChanged - The CursorChanged event occurs when the Cursor property is changed.
  • DockChanged - The DockChanged event occurs when the Dock property is changed.
  • DragDrop - The DragDrop event occurs when a drag-and-drop operation has completed.
  • DragEnter - The DragEnter event occurs when the mouse drags an item into the button.
  • DragLeave - The DragLeave event occurs when an item is dragged out of the button.
  • DragOver - The DragOver event occurs when an item is dragged over the button.
  • EnabledChanged - The EnabledChanged event occurs when the Enabled property is changed.
  • Enter - The Enter event occurs when the button is in focus.
  • FontChanged - The FontChanged event occurs when the Font property is changed.
  • ForeColorChanged - The ForeColorChanged event occurs when the ForeColor property is changed.
  • GiveFeedback - The GiveFeedback event occurs during a drag operation.
  • HelpRequested - The HelpRequested event occurs when the user requests help for the button.
  • KeyDown - The KeyDown event occurs when a key is first pressed.
  • KeyPress - The KeyPress event occurs when the button has focus and the user presses and releases a key.
  • KeyUp - The KeyUp event occurs when a Key is released.
  • Layout - The Layout event occurs when the button is about to layout its contents.
  • Leave - The Leave event occurs when the button loses focus.
  • Locationchanged - The Locationchanged event occurs when the Location property is changed.
  • MarginChanged - The MarginChanged event occurs when the Margin property is changed.
  • MouseCaptureChanged - The MouseCaptureChanged event occurs after the mouse capture has been changed.
  • MouseClick - The MouseClick event occurs when the button has been clicked by the cursor.
  • MouseDown - The MouseDown event occurs when the mouse is over the button and has been pressed.
  • MouseEnter - The MouseEnter event occurs when the mouse is over the button and has been pressed.
  • MouseHover - The MouseHover event occurs when the mouse is stationary when inside the button.
  • MouseLeave - The MouseLeave event occurs when mouse leaves the button.
  • MouseMove - The MouseMove event occurs when the mouse moves over the button.
  • MouseUp - Occurs when the the button is released over the button.
  • Move - Occurs when a control is moved.
  • PaddingChanged - The PaddingChanged event occurs when the Padding property is changed.
  • Paint - The Paint event occurs when the button needs repainting.
  • ParentChanged - The ParentChanged event occurs when the Parent property is changed.
  • PreviewKeyDown - The PreviewKeyDown event occurs just before the KeyDown event is called apon.
  • QueryAccessibilityHelp - The QueryAccessibilityHelp event occurs when an accessibility client requests help for the button.
  • QueryContinueDrag - The QueryContinueDrag event occurs when the mouse drags an item, and Query's the OS as to whether it can drag this kind of object or not.
  • Regionchanged - The Regionchanged event occurs when the Region property is changed.
  • Resize - The Resize event occurs when the button has been resized.
  • RightToLeftChanged - The RightToLeftChanged event occurs when the RightToLeft property is changed.
  • SizeChanged - The SizeChanged event occurs when the Size property is changed.
  • StyleChanged - The StyleChanged event is called when the window style of the button is changed.
  • SystemColorsChanged - The SystemColorsChanged event occurs when the system colors are changed.
  • TabIndexChanged - The TabIndexChanged event occurs when the TabIndex property is changed.
  • TabStopChanged - The TabStopChanged event occurs when the TabStop property is changed.
  • TextChanged - The TextChanged event occurs when the Text property is changed.
  • Validated - The Validated event occurs after the button has been successfully validated.
  • Validating - The Validating event occurs while the button is validating.
  • VisibleChanged - The VisibleChanged event occurs when the Visible property is changed.

4) Examples

What kind of a person would I be if I didn't provide examples of how to use a Button?! I suppose it would be pretty ignorent, seeing as we want to learn how to use the control. For our first example, lets create an Exit Button.

4.1) An Exit Button.

The Exit Button is probably the easiest button to code. But which command is the 'right' exit command? Here we will discuss which one is more suitable.

There are other options, but these ones seem to be more popular.

There is the End keyword that ends the process and closes all the threads on the application. The negative to this is, it doesn't conform to .NET standards.

There is the Me.Close() subroutine, which is a member of the current form. This option conforms to .NET standards, but however if there is more than one form and you want to end the process, and the form isn't set to close on exit, you have a prediciment. :)

Last but certainly not least, there is the Application.Exit() subroutine. I prefer this, because it is a .NET standard and ends all the threads assosiated with the program.

So, now that we know what to do, lets create an exit button.

1) Add a button control to the form.
2) Set the Text property to "Exit".
3) Double-click on the button, this will enter code view and you will be presented with the Button1_Click subroutine (or something simular).
4) In the subroutine add Application.Exit.

You're code should now look something like this:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub

5) Run the application to make sure everything worked properly. If it did, congratulations, you have coded an exit button! :)

4.2) Displaying a message box with the button

Displaying a message box is a very simple method of displaying information. It is effective, straight to the point and used often. We will make our Message Box display "Hello World", for the purpose of this example. But again, we are faced with the same dillema we had in the previous section, which Message Box object should we be using?

The MsgBox() function is a good way of displaying a message. Unfortunatly, it isn't a member of the .NET framework, hence it is not supported any more.

On the other hand, MessageBox.Show() is a member of the .NET framework and does practically the same thing as the MsgBox() function, so we shall be choosing to use this function.

1) Add a button control to the form.
2) Set the Text property to "Say, Hello".
3) Double-click on the button, this will enter code view and you will be presented with the Button1_Click subroutine (or something simular).
4) In the subroutine add MessageBox.Show("Hello World")
5) Run the application! :)

If that worked, you are one step further to creating your own application. :)

5) Conclusion

Thanks for reading though the information in this tutorial. I obviously don't expect you to read all of this, but you can use it as a reference if you like. Remember, if you liked it, rate it. :D

Is This A Good Question/Topic? 1
  • +

Replies To: All you need to know about the button control

#2 Chalie9809  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 51
  • Joined: 29-January 09

Posted 29 January 2009 - 09:50 PM

Best Tutorial Ive seen, Really Good Job, Helped me soo much once again thankyou!!!
Was This Post Helpful? 1
  • +
  • -

#3 princess18  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 79
  • Joined: 07-December 09

Posted 04 September 2010 - 05:42 AM

I like this tutorial! :) however, its not complete. could you please put some examples? for example in this problem:

Simulate a traffic light with a control array consisting of three small square picture boxes placed vertically on a form. initially, the bottom picture box is solid green and the other picture boxes are white. when the tab key is pressed, the middle picture box turns yellow and the bottom picture box turns white. the next time tab is pressed, the top picture box turns red and the middle picture box turns white. subsequent pressing of the tab key cycles through the three colors. Hint: First, place the bottom picture box on the form then the middle picture box and finally the top picture box.

how can i use tab key event??? Please guide me... THANK YOU SO MUCH! :)
Was This Post Helpful? -1
  • +
  • -

#4 muhendisefe  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 05-March 12

Posted 05 March 2012 - 03:55 AM

One of the best tutorials of all i've seen before ! Thank you very much bro!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1