Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Basic drawing program

This tutorial doesn't just show you how to make a simple drawing program, it also teaches you things like error handling. Good for beginners who want some hands-on approach.

On Sunday, March 21st 2004 at 07:05 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.4 with 53 votes)
Contextual Ads
More Visual Basic Resources
Advertisement

Basic drawing program

This tutorial shows you how to make a simple drawing program and this way it also teaches you things like error handling.
Visual Basic is well known for making simple programs fast so this is what we'll do now, a program that opens a bmp file, modifies it and saves it as a new bmp file.
As I said earlier, this tutorial doesn't just show you how to use a brush to modify the content of a PictureBox. It also shows you other stuff, like handling errors so consider it a practical example for Visual Basic beginners.


This is how the program looks (version 0.10). Even MS Paint is much more complex than this program, but for the VisualBasic beginner it is a good start.







You can find the vb project here. Download, run and then we'll analyze the code.


The coding was done in VisualBasic 6.0 (from Visual Studio 6.0).



Dim drawing




First we declare a variable in General Declaration, that will hold either 'True' or 'False', meaning 'draw' or 'don't draw'.
When we press the mouse button on the PictureBox, we want this variable to hold 'True' because we want the mouse cursor to leave a trail (brush).
When the mouse button isn't pressed we want the variable to hold 'False' and 'do not draw'.
We also want the variable to be set to 'False' at the program start, so we add this in Form Load:


Private Sub Form_Load()
drawing = False
End Sub


When we press the mouse button with the cursor on the PictureBox we want the mouse cursor to leave a trail (act like a brush).
This is why we set the 'drawing' variable to 'True' at pctMain_MouseDown:


Private Sub pctMain_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
drawing = True
End Sub


Still, now the cursor doesn't leave any trail because we didn't decided what to do when the drawing variable is set to true:


Private Sub pctMain_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
If drawing = True Then
pctMain.DrawWidth = HScrollBrushSize.Value
pctMain.ForeColor = RGB(VScrollRed, VScrollGreen, VScrollBlue)
pctMain.PSet (X, Y) // The coordinates - the current position of the cursor on the PictureBox
End If
End Sub


The moving of the cursor leaves a trail that has the width of 'HScrollBrushSize.Value' and the color set by the 3 ScrollBars ('RGB(VScrollRed, VScrollGreen, VScrollBlue)').
If the mouse button is released we should stop drawing. That is why we use:


Private Sub pctMain_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
drawing = False
End Sub




We can change the size of the circle using either the ScrollBar or the TextBox.
For changing the size using the ScrollBar, the code is the following:


shpCurr.BorderWidth = HScrollBrushSize.Value
txtBrushSize.Text = HScrollBrushSize.Value


We increase the BorderWidth property of the shape to the value of the ScrollBar. We also update the alternative way to change the size of the circle, the TextBox.
Looks good, but the size changes only when we press the arrows of the ScrollBar. When we drag the slider on the ScrollBar, the shape doesn't get bigger/smaller.
We fix this by calling the Sub from 'HScrollBrushSize Scroll', because when we slide we want everything to act the same as when we use the arrow buttons:


Private Sub HScrollBrushSize_Scroll()
HScrollBrushSize_Change
End Sub




Now we set up the alternative way for making the shape bigger/smaller, the TextBox:


Private Sub txtBrushSize_Change()
If txtBrushSize.Text > 30 Then
txtBrushSize.Text = 30
End If
HScrollBrushSize.Value = txtBrushSize.Text
End Sub


With 'HScrollBrushSize.Value = txtBrushSize.Text' we update the ScrollBar to the value from the TextBox.


What's with the 'If' condition you ask? The 'Max' attribute of the ScrollBar is set to 30. This means we shouldn't have a circle bigger than 30. If we insert a value bigger than 30, it will be reseted to the biggest possible value, 30.



'VScrollRed', 'VScrollGreen' and 'VScrollBlue' form a RGB value that changes the color of the brush.
Concerning the alternative use of the 'TextBox' for choosing a RGB value, they act similar to the 'HScrollBrushSize' and 'txtBrushSize'. They change at the same time and support a maximum value of 255:


Private Sub VScrollRed_Change()
shpCurr.BorderColor = RGB(VScrollRed, VScrollGreen, VScrollBlue)
txtRVal.Text = VScrollRed.Value
End Sub


Instead of rewriting the code for 'VScrollRed_Scroll()' we can call the 'VScrollRed_Change' Sub:


Private Sub VScrollRed_Scroll()
VScrollRed_Change
End Sub


The same works for the other two:


Private Sub VScrollGreen_Change()
shpCurr.BorderColor = RGB(VScrollRed, VScrollGreen, VScrollBlue)
txtGVal.Text = VScrollGreen.Value
End Sub



Private Sub VScrollGreen_Scroll()
VScrollGreen_Change
End Sub



Private Sub VScrollBlue_Change()
shpCurr.BorderColor = RGB(VScrollRed, VScrollGreen, VScrollBlue)
txtBVal.Text = VScrollBlue.Value
End Sub



Private Sub VScrollBlue_Scroll()
VScrollBlue_Change
End Sub





When we click the 'Load' button we want to check if the path in 'txtLoad' is correct and if the file exists:


On Error GoTo LoadPicError
pctMain.Picture = LoadPicture(txtLoad.Text)
LoadPicError:
    Select Case Err.Number
    Case 53
        MsgBox "Path doesn't exist.", vbCritical, "Wrong path"
    Case 75
        MsgBox "File doesn't exist.", vbCritical, "Wrong file"
    End Select


When we load a file there can be two (or more) possible errors. If the path is incorrect, or if the path is correct, but the file doesn't exist in the specified folder.
This is why we use 'On Error GoTo LoadPicError' - we tell the program if an error is found to go to the line with 'LoadPicError:'.
There we have two cases of error number messages. If the error number (Err.Number) is 53, it means the path isn't correct. If the error number is 75 it means the path is correct, but there is no file with that name.


At the save button we have the following code:


Private Sub cmdSave_Click()
On Error GoTo SavePicError
Set pctMain.Picture = pctMain.Image
SavePicture pctMain.Picture, txtSave.Text
SavePicError:
    Select Case Err.Number
    Case 76
        MsgBox "Path doesn't exist.", vbCritical, "Wrong path"
    End Select
End Sub


The same, if there happens to be an error, probably this would be because the path isn't correct (the folder in which you selected to save the image doesn't exist). And that error has the 76 number.


Warning! The file name must have the bmp extension. A good save path for example is 'c:\newfile.bmp'



When you click on the 'txtLoad' TextBox the 'Enter the path to the BMP file to load' message disappears. If we leave the TextBox empty and select something else on the form (LostFocus), the text appears back. Though, if we write something in the TextBox and select something else on the form, the text doesn't appear anymore.
This is done using:


Private Sub txtLoad_GotFocus()
If txtLoad.Text = "Enter the path to the BMP file to load" Then
txtLoad.Text = ""
End If
End Sub


and


Private Sub txtLoad_LostFocus()
If txtLoad.Text = "" Then
txtLoad.Text = "Enter the path to the BMP file to load"
End If
End Sub


This is the way it should because if we type a path in 'txtLoad' and click the 'cmdLoad' button, the TextBox would be reseted to 'Enter the path to the BMP file to load', and that's not what we want to.
Therefore in the first piece of code (txtLoad_GotFocus()) we check to see if the TextBox contains the default text. If it does we reset it to "", that means nothing, nada, blank...
When the 'txtLoad' TextBox loses focus we want to check it if it's empty. If it's empty, that means that the user didn't type anything, and it's safe to come back to the default message.


The same technique we use on 'txtSave':


Private Sub txtSave_GotFocus()
If txtSave.Text = "Enter the path where the BMP file will be saved" Then
txtSave.Text = ""
End If
End Sub


and


Private Sub txtSave_LostFocus()
If txtSave.Text = "" Then
txtSave.Text = "Enter the path where the BMP file will be saved"
End If
End Sub





Finally, in the 'About' 'MsgBox' we use a method to break the text into several lines:


MsgBox "Made by Andrei Pociu for Geekpedia" & vbCr & "email@domain.com" & vbCr & vbCr & " Copyright (C) 2004 Geekpedia.com", vbOK + vbInformation, "About Drawing"

'vbOK + vbInformation' is the type of 'MsgBox' we want, one with an OK button and vbInformation icon.



If this tutorial will get a high rate maybe it will continue with a part II, where you'll learn how to make your program draw shapes and other things .
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Mihai Potra on Wednesday, April 14th 2004 at 09:42 PM

Another way to ease your work is Visual Basic is using arrays.
For instance, instead of creating 3 scrollbars and 3 textboxes with different names we would create an index array for controls (use the same name but modify the Index field value). After creating these arrays (scrollbars and textboxes) you will notice that in your Procedures, a new parameter appeared "Index as Integer" on the first place.
So instead of:

Private Sub VScrollRed_Scroll()
VScrollRed_Change
End Sub

you'll have:

Private Sub VScroll_Scroll(Index as Integer)
VScroll_Change (Index)
End Sub

and furthermore:

Private Sub VScroll_Change(Index as Integer)
shpCurr.BorderColor = RGB(VScroll(0).Value, VScroll(1).Value, VScroll(2).Value)
txtVal(2).Text = VScroll(2).Value
End Sub

Well, I hope you got the big picture of it.

Conclusion: by using control arrays and variable arrays you shorten the length of your source code and create an easier to understand code.

by PAt on Saturday, June 12th 2004 at 07:33 PM

Thanks for your tutorial, i am studing Visual Basic and i have been reading and trying to get a hang of it but i could never get a book that would actually show how to code. They always showed you the basics or an overview. thanks really helped

by Ibrahim Shareef on Monday, September 6th 2004 at 06:15 AM

great

by matt on Friday, October 8th 2004 at 02:02 PM

A good tutorial, some more images would of been nice but the code is fine so thats all that matters.

by Jake on Saturday, November 20th 2004 at 12:06 PM

Finally, a tutorial i can understand, the tutorials at www.microsoft.com and wrox tutorials had me stuck, cheers Andrei, im finally going somewhere
jake

by Peter Corp Traneader on Saturday, February 12th 2005 at 07:27 AM

Thank You. I'm downloaded your source code

by Riaan on Monday, February 14th 2005 at 03:01 AM

Sweet code ... Thanx

by Slinky on Saturday, June 11th 2005 at 02:26 AM

Thanks, this code is amazingly simple and works perfectly. I've used this tutorial to make my own small drawing program which works like a dream.

by Sudeep(#1114) on Wednesday, November 16th 2005 at 02:50 AM

i am a begineer student of vb. the above code looks so simpler and i have thought it will work perfectly

by M.RAMESH KUMARR on Monday, November 28th 2005 at 12:20 AM

EXCELLENT TUTORIAL FOR BEGINNERS.

M.RAMESH KUMARR

by marison on Friday, March 3rd 2006 at 04:42 AM

thank you very much for the tutorial, i needed that for my project and now i have learned a lot from you..thanks again..

by ShuckyD on Friday, December 15th 2006 at 10:44 AM

really well put together tutorial, infortunately since i am using VS.Net i cant get it to work, i tried coding from what you have written above, but i ran into a problem at the pct.DrawWidth, that among other things is different from the verision you used and the one im using, i used its upgrade wizzard on your code, but it still wont compile, none the less still a great tutorial i would love to figure out how to code one day

by michael Taddele on Wednesday, April 4th 2007 at 12:46 PM

We need advice on how we can develop advanced drawings (Mechanical Gear) using visual Basic Graphics.
We thank you in advance for your anticipated cooperation.

by on Thursday, February 14th 2008 at 12:47 PM

3ew

by Strife26 on Tuesday, December 23rd 2008 at 08:07 AM

This is a good guide, helped me with a class project!

by Augst6 on Tuesday, August 25th 2009 at 04:26 AM

Can you post the program that u made?
I'm a bit confused with the codes...

by Nilima on Thursday, September 24th 2009 at 12:07 AM

plz send me the code to implement paint brush in java painter. (as early as possible).

by ccccc on Wednesday, October 21st 2009 at 05:03 AM

Thnx for sharing^^. It's really a great help!

by kasuy on Monday, January 11th 2010 at 03:43 AM

ang tae tae nmn

by kasuy on Monday, January 11th 2010 at 03:43 AM

ang tae tae nmn

by kasuy on Monday, January 11th 2010 at 03:43 AM

ang tae tae nmn

by poop on Saturday, April 3rd 2010 at 12:52 PM

Hi

by Ryan on Wednesday, June 29th 2011 at 08:11 AM

is the download supposed to be a rar file. please email me.

by awe ltd on Tuesday, August 23rd 2011 at 09:37 AM

Wow - just shows how powerful Visual Basic is!

Thanks for the code - it's a good starting place to have a fiddle with some of the variables in Visual Basic.

by Cazare Predeal on Friday, September 2nd 2011 at 09:12 AM

Thanks for the tutorial, it is very useful for us.

by Recruitment to Recruitment Hong Kong on Wednesday, October 12th 2011 at 07:41 AM

The post is actually the freshest on this laudable subject. I harmonize with your conclusions and will thirstily look forward to see your approaching updates. <a href="http://www.carlinhall.co.uk/">Recruitment to Recruitment Hong Kong</a>

by Recruitment to Recruitment Hong Kong on Wednesday, October 12th 2011 at 07:42 AM

Best post

by data entry pakistan on Thursday, October 13th 2011 at 07:38 AM

It’s really great stuff overall, I just wanted to say thank you. I am looking forward to another great article from your side.

by software review on Saturday, November 5th 2011 at 03:13 AM

Great work you have done by sharing them to all. simply superb. Thanks for a nice share you have given to us with such an large collection of information regards.

by registry cleaner on Sunday, November 6th 2011 at 11:03 AM

There are all kinds of illustrating and editing programs, so those of us working in design area have plenty of tools to choose from. Technology is by our side. For those who may have probably used several encoders available in this industry more than once, I assume this is an easy thing to achieve. I for one have barely managed to deal with the file sharing services. which means accessible things to anyone. I just learned how to deal with disk space, restriction, compatibility and some codecs. As you display it right here, step by step, it shouldn`t be too hard to make it. I think I will take a better look at this presentation and give it a try to this method.

by how to get a credit card with no credit on Monday, December 12th 2011 at 12:42 PM

Hey do you know why my phone shuts off almost every other time I close the phone shut?! It's driving me crazy and its not because I have low battery.

by Los Angeles Self Storage on Saturday, December 17th 2011 at 05:08 PM

Here I found your blog to be very worthwhile. I am quite excited with all the article content of your site.

by funeral flower arrangements on Saturday, January 21st 2012 at 05:22 PM

Interesting topic what you have shared with us. Your writing skill is really very appreciative. I love when you share your views through the best articles.Keep sharing and posting articles like these.This article has helped me a lot.Keep posting this stuff.

by free classified ads on Monday, January 23rd 2012 at 04:16 PM

Visual Basic has always been my favorite, because it makes everything so easy, even I can understand. I love drawing on my computer, but so far I couldn't manage with any software. Fortunately, this one will help me express myself virtually, as well. Thanks for this tutorial, it's been of help.

by Rice Crispy Treats on Sunday, January 29th 2012 at 04:05 PM

I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.

by memory foam gel mattress on Sunday, February 19th 2012 at 03:11 PM

You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand.

by hermes constance bag price on Monday, February 20th 2012 at 07:36 PM

With her Patti Smith-esque, <a href="http://www.cheapjordanshoesoutletonline.com" title="cheap jordan shoes">cheap jordan shoes</a> raven-colored locks and an editorial in the latest issue of Love shot by Mario Testino, <a href="http://www.cheapjordanshoesoutletonline.com/basketball-shoes-c-1.html" title="jordan shoes for cheap">jordan shoes for cheap</a> Stasiuk has that edgy look-of-the-moment, <a href="http://www.cheapjordanshoesoutletonline.com/skate-shoes-c-5.html" title="cheap air jordan shoes">cheap air jordan shoes</a> which should take her far in Europe. But fashion is forever unpredictable, and many of the best newcomers wait to make their debut in Milan or Paris. <a href="http://www.hermesconstanceoutlet.com" title="hermes constance">hermes constance</a> So you never know. Plus, just when you thought it couldn’t possibly get any better than a week-long Giveaway Extravaganza with some of our favorite advertisers, <a href="http://www.hermesconstanceoutlet.com/hermes-constance-bags-5" title="constance hermes">constance hermes</a> we added even more dazzling giveaways to the mix.<a href="http://www.hermesconstanceoutlet.com/hermes-bags-2" title="hermes constance bag">hermes constance bag</a> Yep, it’s been awesome. And since we know you lovelies have been sitting.on.the.edge.of.Josie Maran has certainly been reaping them since she graduated from model to beauty entrepreneur. Maran’s eponymous natural-minded line that’s entirely based around the miraculous skincare wonder that is Moroccan-born argan oil is a bona fide hit, <a href="http://www.hermesconstanceoutlet.com/hermes-handbags-11" title="hermes constance price">hermes constance price</a> and her latest product celebrates the range’s star ingredient particularly well <a href="http://www.ouruggboots.us/ugg-classic-short-boots-c-2.html">ugg boots</a>

by Travel on Sunday, February 26th 2012 at 08:53 AM

thanks

by Tagesgeldkonto on Thursday, March 8th 2012 at 10:16 AM

Une marque est plus qu'un logo ou une image. Elle affecte la première impression à l'organisation et la façon dont votre travail est perçu et apprécié par les gens.

by AppLogic on Tuesday, March 13th 2012 at 06:37 AM

Visual Basic looks very simple, indeed, but I've heard it does some pretty great things and even though Paint may seem more complex, it doesn't have so many applications as this one. I can't wait to try it, thanks for giving us these tips!

by Programas fidelizacion on Thursday, March 15th 2012 at 06:21 AM

Software para gestionar Programas fidelizacion clientes, Software fidelizacion clientes y Tarjetas de fidelizacion y puntos. Precios económicos. Consúltanos

by tatuaggi stelle on Thursday, March 22nd 2012 at 01:11 AM

I love when you share your views through the best articles.Keep sharing and posting articles like these.This article has helped me a lot.Keep posting this stuff.

by where can i buy steroids on Saturday, March 24th 2012 at 01:56 AM

I am quite excited with all the article content of your site.

by phen375 review on Saturday, March 24th 2012 at 09:48 AM

x. It also shows you other stuff, like handling errors so consider it a practical example for Visual Basic beginners.

by here on Thursday, May 3rd 2012 at 01:40 AM

Computer aided design is an art. People must have very much talent and inspiration to get good results.

by code avantage elle passions on Monday, May 14th 2012 at 08:35 AM

it's nice to share views online. and even publishing articles commecomme this one is a very good idea

by 1N4148 on Tuesday, May 15th 2012 at 07:52 AM

I never got really acquainted to Paint, it is barbarian and made for little children. I usually use it when I want to save a print screen image. Visual Basic might just be what I need to make things more pleasant.

by online umpire training on Thursday, May 17th 2012 at 02:09 AM

Thank you for sharing such great information with us. I really appreciate everything that you've done here and am glad to know that you really care about the world that we live in

by online umpire training on Thursday, May 17th 2012 at 02:09 AM

Thank you for sharing such great information with us. I really appreciate everything that you've done here and am glad to know that you really care about the world that we live in

by Granny Pussy on Monday, May 21st 2012 at 04:23 PM

I could also gain several of my ranches for marketing substance for you all budy who come up here. i think so it is very useful and knowledgeable. I would like to thank you for the efforts.

by OpenVPN reviews on Friday, May 25th 2012 at 10:37 PM

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well.

by Mundgeruch bekaempfen on Sunday, May 27th 2012 at 02:26 AM

Just what I was looking for and quite thorough as well. Thanks for posting this, I saw a couple other similar posts but yours was the best so far. I hope it stays updated, take care.


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs Visual Basic Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia
Other Resources
Bargain EZ Tech Coupons & Deals