Come back to home page

Give your form any shape you want (Form; VB.NET)Download

How does a form look like in VB.NET?

Don't you feel like changing this shape for some of your applications like following:

Doing this was hell of a job in Visual Basic 6. In .net, it is a matter of two lines of code!!

The Code

Private Sub frmMain_Paint(ByVal sender As ObjectByVal e As System.Windows.Forms.PaintEventArgs) _
Handles MyBase
.Paint
    Dim img As Bitmap = Me.BackgroundImage
    img.MakeTransparent(img.GetPixel(0, 0))
    Me.TransparencyKey = img.GetPixel(0, 0)
End Sub

For quick understanding, let is check the points to notice in the above code:

  • It is better to write the code in Paint Event of the form.
     
  • Set the image you want as your form's shape as BackgroundImage of the form. However, if you want to do everything at run time, you can load the image directly from the file. If you want to this, check the following point.
     
  • In the first line of code, we have created a bitmap object (img) which holds our image for processing. We will process the image through this object. The code to get a reference to the background image of the form in img object is:

    Dim img As Bitmap = Me.BackgroundImage

    However, if you want to get the reference of an image directly from the file, you can use the following code:

    Dim img As New Bitmap("filename")
     
  • The second line uses the MakeTransparent method of bitmap class to make the specified color transparent in the image. (This is what we are trying to achieve in this code). The color can be specified directly also (example: Color.White or Color.Red, etc.), but I prefer to use the first pixel of the image in this case because in this case I don't have to bother about the background color or the image and in 99.99% cases the first pixel does not hold any part of the image but it does hold a part of the background.
     
  • Once the required color is made transparent in the image. We need set the TransparencyKey of our form to the color we want to make transparent as this will tell the form to display the specified region as transparent.

Although the code and technique is simple, I understand that there might be some issues. If you think that I can help you in any way, please feel free to contact me at rahul@coder000.com.