View Full Version : Free programming lessons
Vodstok
11-20-2006, 12:43 PM
Okay, i got a bug up my butt and decided to give a little bit of insight into my professional life. So, for anyone who is interested, i am going to show how to make some simple programs in C# (C-sharp), my language of choice.
for starters, you will need the .net framework. I prefer the 2.0 framework, as it is the latest and greatest, and is required to use Visual Studio express (more on that in a second)
http://www.microsoft.com/downloads/details.aspx?FamilyID=0856EACB-4362-4B0D-8EDD-AAB15C5E04F5&displaylang=en
this is the link to get Visual C# express:
http://go.microsoft.com/fwlink/?LinkId=51411&clcid=0x409
you may need a .net passport. Sign up and get one if you dont already have one. Dont worry, Microsoft could care less about you, so its not like they are going to own your soul for signing up.
Install them both, the framework first. Once you have that, we will move on to our first lesson.
Vodstok
11-20-2006, 12:56 PM
fire up visual studio (from here on to be called "VCS" for "Visual C# Studio"). complete any config wizards it has. Register it to avoid getting hounded every time you open it.
first off, we are going to start a project.
on the start page, click "Project..." after "Create"
By default, it should have "Windows Application" selected. in the "Name" line, type "Lesson1", then hit "OK". this will make a new programproject called "Lesson1". (crazy how that works....)
VCS will create some fun little files for you, and the main window will have an ugly little box that says "Form 1". you should have a menu that says "Toolbox". In Toolbox, there will be an area called "Common Controls". click on "Button". now click on the ugly little "Form 1". See? There's a button now!
Double-click the button. Dont be scared. this is where you program. you will see something that looks like this:
private void button1_Click(object sender, EventArgs e)
{
}
Make it look like this:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("YOU CLICKED A BUTTON!");
}
NOTE: C# is case sensitive, so ANYTHING not inside quotation marks (in this case, anyhing NOT "YOU CLICKED A BUTTON!") HAS to be typed as I have shown.
Did that? Good. now hit "Ctrl-f5" on your keyboard. This will compile and launch your program.
When the new ugly little window pops up, click the button. YAY! see? You just wrote a verrry simple program. Pat yourself on the back.
close your little program and go back to VCS. hit ctrl-shift-S. A save dialogue will come up. just hit "save". This way, your project will still be there if your computer suddenly reboots.
Vodstok
11-21-2006, 04:36 AM
Any interest in this, or should i just let it die?
VampiricClown
11-21-2006, 07:18 AM
I'm interested in it. I can't start on it today, but possibly tomorrow...
Vodstok
11-21-2006, 07:26 AM
I will probably keep posting little lessons even if i get no feedback. I figure its a nice way to get some exposure for people who are curious but dont know where to look.
Phalanx
11-21-2006, 08:53 AM
The chick might take you up on it, man...me, I get annoyed with spreadsheets.
Nice idea though.
stygianwitch
11-21-2006, 09:42 AM
i'll be giving it a go too, but expect pm's when i don't understand wtf it all means... i'm one of these weird people who have to understand what the instuction will do not just see the end result, so keep ya inbox cleared ;)
Vodstok
11-21-2006, 10:14 AM
i'll be giving it a go too, but expect pm's when i don't understand wtf it all means... i'm one of these weird people who have to understand what the instuction will do not just see the end result, so keep ya inbox cleared ;)
PM if oyu want, but asking questions publically would be a good idea so that everyone can benefit from the explanation :D
stubbornforgey
11-21-2006, 10:16 AM
shit!!
FINALLY..a good thread..nice vodstock..
ppl may not be replying but they are taking notes.
stygianwitch
11-21-2006, 10:17 AM
PM if oyu want, but asking questions publically would be a good idea so that everyone can benefit from the explanation :D
you got a deal, but be warned i can be a real pain in the ass til i understand :o
Vodstok
11-21-2006, 11:03 AM
you got a deal, but be warned i can be a real pain in the ass til i understand :o
No biggie. i will do my best to include some programming theory so you know WHY it works, not just how.
Here's one for starters. C# is based on C, as well as Java (which is based on C...). They are what is called "Object Oriented (or "OO") languages. The objects it refers to can be thought of as tools. Dont get too intimidated, but the .Net framework (the toolbox you use in C#) has something ridiculous like 29,000 objects... but that is another tale for another day.
how about lesson 2? This is more fun than just making a button.
for starters, lets buy some more real estate. In "Form1.cs [Design]", click any part of the form except the button. Now find Properties in the sidebar. scroll down until you find Size. type this: 640, 480 and hit enter.
the form should be bigger now. now, double clickk the form itself. it should take you to the code, and create this:
private void Form1_Load(object sender, EventArgs e)
{
}
Vodstok
11-21-2006, 11:10 AM
now, go to "tools" and click on GroupBox. place it where you want it on the form. next, again in tools click "Timer" and place that in the form also. Dont worry, it will appear in a bar below the form. this is what it is supposed to do, since the timer is something that works in the background without any visual representation.
Now, double click "timer1" in the bar. You should see this now:
private void timer1_Tick(object sender, EventArgs e)
{
}
this is what the timer will do on every "tick". Imagine a clock that does something on every tick of the second hand. We are going to make ours change some colors in a neat fashion.
Go up to the block that has Form1_Load and type this:
in between these:
{
}
so we want this:
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
}
Vodstok
11-21-2006, 11:47 AM
now, we want this:
private void timer1_Tick(object sender, EventArgs e)
{
Random r = new Random();
int i = r.Next(0, 255);
int y = r.Next(0, 255);
int u = r.Next(0, 255);
groupBox1.BackColor = Color.FromArgb(i,y,u);
groupBox1.ForeColor = Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255));
}
i will explain this. Also, from now on anythign in this color, is an explanantion of theory, and can be ignored, unless you want to know WHY.
timer1_Tick, Form1_Load, and button1_Click are events. Most Object Oriented Programming is also Event Driven, meaning something has to happen for code to run. Clicking the button is an event you initiate. Running the program runs Form1_Load, and the nature of the Timer control causes it to fire off the timer1_Tick event on a regular basis (i will explain the ins and outs of the Timer control at another time)
anyway, this is the breakdown of the code above.
Random r = new Random();
in this line, we instantiate a Random object. Think of it as grabbing a hammer. we instantiate it as "r". So we tak eout a hammer, now we will call that hammer "r". No other hammers can be r, nor can any wrenches, screwdrivers, etc.
r is a new Random.
now, we declare some variables. If you have taken Algebra, you are at least familiar with the concept of a variable. Inprogramming, variables arent always numbers, but right here they are.
this:
int i = r.Next(0, 255);
int y = r.Next(0, 255);
int u = r.Next(0, 255);
translates to this:
make an integer object called i, and make it's value some random number from 0 to 255. (more on why in a minute)
from now on, these letters (i,y,and u) will be a specific number.
the next part:
groupBox1.BackColor = Color.FromArgb(i,y,u);
groupBox1.ForeColor = Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255));
is where the fun happens. groupBox1.BackColor defines the background color of the groupbox i had you guys create earlier. Color.FromArgb is a neat little Method that takes number values from 0 through 255 and translates them into a color. Anyone who has played with custom colors on your computer hasd probably seen that every color possible in a computer can be defined with varying values of Red Blue and Green (hence RGB). this lets oyu do it with numbers. which makes for some fun.
Anyway, the back color will change to whatever combination of numbers your 3 int variables recieved.
the one with groupBox1.ForeColor defines the text color of the groupbox. this one is here to illustrate that you dont HAVE to assign variables when calling r.Next. let me know if you have any questions.
For fun, go back to Form1.cs [Design] and click on the groupbox, and find Text in properties. Chenge it to Colors! or whatever text you want. now hit Ctrl-F5 to compile and launch your program.
Isnt that fun? Kind of psychadelic...
here is how it works. When you launch the program, Form1_Load fires off as part of the program startup. It in turn runs timer1.Start();, which gets the timer1 ball rolling. Now, every second, timer1 executes timer1_Tick, thereby generating random numbers and getting a color value from them, and assigning the new colors to the text and background of the groupbox, making it all flashy and fun. :)
Vodstok
11-22-2006, 04:46 PM
Bump. I can not believe the number of views this thing has been geting...:)
stygianwitch
11-23-2006, 01:55 PM
I can not believe the number of views this thing has been getting...:)
it's an excellent thread, along with the web site lessons, why wouldn't they, finally something useful :) :cool:
i'm copy and pasting everything... and backing it up, i really want to have a good go at this, can't start it this weekend but as soon as i get back....:)
Spallalala
11-24-2006, 02:20 AM
Umm..what the fuck happened to my posts in here? Why have they gone..Anyway. Uh..Im confused now haha. Gimme about 2 days to read that lot and try it. I got the hang on making a simple htm page. Even added a background too hehe. The programs you mentioned for us to download are good. But yeah slowwwly gettin the hang of this stuff. I aint gonna give up tho.
Spallalala
11-24-2006, 03:48 AM
Oh I see now..2 different threads hahah woopsy
Vodstok
12-26-2006, 05:34 AM
Okay, how about a new lesson? We will stick with the same project and add to it.
Wanna make a .Jpg image with some text? No? Too bad.
here we go. Open your project, and look at Forms.cs. Way at the top, you should see this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
Add this to the end of that list (remember, C# is CASE SENSITIVE):
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
Now, go to Form1.cs [Design]. Drag and drop a new button onto the form. Right click it and select "Properties". The properties pane shoudl appear (if it isnt already there). There is a long list of stuff, but find (Name). Change the name to btnImage.
Why the weird name? There is this fun little thing i mentioned before called "Best Practices". They are a list of suggestions to keep code clean, consistent, and easy to read. As a programmer, i cant tell you the number of times i have worked on projects where the guy before me didnt use this, and it is a godamn nightmare... Never mind going back to something you wrote a year before, and knew inside and out, and now you are looking at it with fresh eyes and wondering why you called a textbox "Zombie".
The standard goes like this, start with lowercase, and on the first part that is a new word, use uppercase, and the same for any other word there after. Keep it simple but descriptive.
Example, i renamed the button that we will use to creat the image btnImage. (sorry if this seems condescending to some, but i would rather not leave out anything.) btn for Button, and Image for Image. If i was going to make another one that saved the image, i might call it btnImageSave, or somethingto that effect.
change the text of the button to Make Image.
now, drag and drop a textBox onto the form and stretch it out to hold more text (this is only aesthetic). Rename it tbImage. Now, double-click btnImage.
And we get:
private void btnImage_Click(object sender, EventArgs e)
{
}
Which should be getting a little familiar now.
Now, things start to get a little more complicated here.
Type all of this, then i will explain why:
private void btnImage_Click(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(300, 300, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bm);
Rectangle r = new Rectangle(0, 0, 300, 300);
g.FillRectangle(new SolidBrush(Color.Red), r);
SolidBrush sb = new SolidBrush(Color.Black);
g.DrawString(tbImage.Text, new Font(FontFamily.GenericSansSerif,12), sb, 10, 10);
g.SmoothingMode = SmoothingMode.AntiAlias;
string path = @"c:\";
bm.Save(path + "mine.jpg", ImageFormat.Jpeg);
}
Vodstok
12-26-2006, 06:07 AM
And here is the breakdown:
For starters, we instantiate a Bitmap object, name it "bm" (for bitmap, not bowel movement), and set it's height and width to 300 pixels each, and set it to be a 24 bit image (so we can eventually use all the fancy colors we want).
Bitmap bm = new Bitmap(300, 300, PixelFormat.Format24bppRgb);
next, we instantiate a Graphics object. Think of this as opening photoshop, as it allows us to manipulate our new (empty) bitmap image. we use Graphics.FromImage(bm) to grab the image.
next is Rectangle r = new Rectangle(0, 0, 300, 300);
this created a new Rectangle object, to be used by the Graphics object. This is, in a manner of speaking, a piece of construction paper. the 2 0s set the rectangle's upper left corner position, for our needs, it will be at th pixel located at x 0 and y 0 (eek, geometry... Remember 9th grade math and you will be okay, but dont be afraid to ask if you dont know or remember what i am talking about), and it will be 300 pixels tall and 300 pixels wide. This is how we set the background for our image.
Now, we "fill" the rectangle with color:
g.FillRectangle(new SolidBrush(Color.Red), r);
We use "Brushes" to paint colors in ourt programming. A SloidBrush is simply a one color brush. if you have ever used Paint in Windows, this is the same as clikcing on the bucket, and using red.
Next, we instantiate a new SolidBrush:
SolidBrush sb = new SolidBrush(Color.Black);
Why am I instantiating thisone with a name, and i didnt for the last one? because. No really, that is it. A deeper menaing would be this:
In the first example (where i decalred a new solidbrush in g.FillRectangle), i wanted to make the rectangle red, but i have no need or desire to use that brush for anything else.
However, I instantiated sb so that it can be reused. I can now use sb for any brush needs i want, i just have to manipulate it's properties. Plus, for what i will do later, it will make things easier. Why not instantiate a new named one every time? Well, although it's not as big an issue with C# as it is with older lanbguages like C++, every time you instantiate an object, you use up a little bit of your pc's memory. On this scale, it's like a grain of sand in the Sahara, big deal if it's the size of a buick. When you start getting into bigger applications that are running with thousands or even millions of grains of sand, tyhose buicks begin to add up, and make your machione run like crap, or fill up your memory and crash it. That is bad programming. So even on a small scale, we keep things clean and neat, so that we are intimately familiar with the good practices, in case we ever need to make a million buick-sized grains of sand.
okay, next step:
g.DrawString(tbImage.Text, new Font(FontFamily.GenericSansSerif,12), sb, 10, 10);
g.DrawString is like using a pencil to write text onto our construction paper. tbImage.Text is the text that you will be typing into your text box when the program runs. Next, we need to tell g the font to use. We instatiate a new one, and tell it to use a nice generic font, and to be 12 pixels high (very standard stuff). We tell it to use sb to draw, basically sb becomes our pencil, and it writes in black. we tell it to begin in the 10th pixel on the x axis, and the 10th pixel on the y axis, so it isnt stuck up in a corner somewhere.
this:
g.SmoothingMode = SmoothingMode.AntiAlias;
Just makes it come out nicer, it smooths over rough edges so you dont get those ugly jagged edges on round letters.
this little guy:
string path = @"c:\";
is where the program will save our new file. strings are simply text. Any character can be a string as long as it is contained in "".
Here is where something really simple gets very complicated. Why is there an @ sign out front? Well, C# has something called "Escape Characters", and the biggest one is \ (backslash). it is used to turn characters whithin strings into a part of that string, as opposed to acting upon it. To clarify:
this in code: "Bob is a tool."
will Look like this when displayed by a program:
Bob is a tool.
And this in code: "Bob is a \"tool\"."
will Look like this when displayed by a program:
Bob is a "tool".
Now, if we do it like this:
"Bob is a "tool\"."
We will get an error when we try to compile the code. same if we remove the second \. this is because adding \ in front of " tells the compiler that we want the quotation marks to be part of the text, not encapsulate it. Cool, no?
But it adds a complication to things, because as a result of this behavior, the compiler looks at any backslash as an escape character, and therefore causes problems itself when used. you can fix this in one of 2 ways:
use \\ if you need to use a backslash in text (and for using files, we often need to explicitly set the filepath), OR, we can add @ to the front, which tells the compiler to ignore any backslashes, and treat them as part of the text. No one bothered to teach me this little fact in the beginningand it lead to some horrible headaches.
We could have just as easily dont this for our path:
"c:\\", and it would be looked at by the program as "c:\" when it ran.
Lastly, we do this:
bm.Save(path + "mine.jpg", ImageFormat.Jpeg);
this takes our little path, adds to it a filename (mine.jpg), and saves it as a jpg image, which i am sure all of us are familiar with.
now, hit ctrl-f5, and your program should run. Type something into the textbox (make it vulgar, it's more fun that way), then click the Make Image button. Go to your C drive, and mine.jpg should be hangingout in there. Open it up and marvel at your masterful programming skills.
Now, want to make things a bit more interesting? I thought so.
Vodstok
12-26-2006, 06:44 AM
Okay, lets mix things up a little. underneath you last block of code, type this:
private Color Randy
{
get
{
Random r = new Random();
int i = r.Next(0, 255);
int y = r.Next(0, 255);
int u = r.Next(0, 255);
Color c = Color.FromArgb(i, y, u);
return c;
}
}
this does the same thing we did back when we made the groupBox xchange color, only now we have created a Field. We can now call this Color anywhere in the code simply by typing Randy.
go back up to our btnImage_Click event, and make some changes:
private void btnImage_Click(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(300, 300, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bm);
Rectangle r = new Rectangle(0, 0, 300, 300);
//g.FillRectangle(new SolidBrush(ColorRed), r);
//SolidBrush sb = new SolidBrush(Color.Black);
//g.DrawString(tbImage.Text, new Font(FontFamily.GenericSansSerif,12), sb, 10, 10);
g.SmoothingMode = SmoothingMode.AntiAlias;
string path = @"c:\";
bm.Save(path + "mine.jpg", ImageFormat.Jpeg);
}
I know what you are thinking; What's with the // guys and the new green? Those are called "Comment Tags", they tell the compiler to ignore anything on the same line, typed after them. They exist so that, like best practices in naming, you can make your code clearer to yourself and anyone else who may be looking at the code in the future. In this case, it takes lines of code that we were using previously, and makes them invisible in a sense, so that we dont have to actually erase them (in case we want to use them again), but we dont have to worry about them causing any problems with the new code. More on commenting at a later time
private void btnImage_Click(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(300, 300, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bm);
Rectangle r = new Rectangle(0, 0, 300, 300);
//g.FillRectangle(new SolidBrush(ColorRed), r);
g.FillRectangle(new LinearGradientBrush(new Rectangle(0, 0, 300, 300), groupBox1.ForeColor, groupBox1.BackColor, 180), r);
//SolidBrush sb = new SolidBrush(Color.Black);
LinearGradientBrush lgb = new LinearGradientBrush(new Rectangle(0, 0, 300, 300), Randy, Randy, 90);
//g.DrawString(tbImage.Text, new Font(FontFamily.GenericSansSerif,12), sb, 10, 10);
g.DrawString(tbImage.Text, new Font(FontFamily.GenericSansSerif,12,FontStyle.Bold ), lgb, 10, 10);
g.SmoothingMode = SmoothingMode.AntiAlias;
string path = @"c:\";
bm.Save(path + "mine.jpg", ImageFormat.Jpeg);
}
What are these exciting new lines, you ask? Well, rather than the boring old SolidBrush, with it's one color, we have gone with Linear Gradient Brushes. They make a nice transition from one color to another. here is how they break down:
we instantiate a new one, like we do with most of this monsters, and we give it a new set of coordinates, that exactly mimic our rectangle friend (if we re-use the rectangle we already have for everything, it can get messy). For LinearGradientBrushes, we need to set 2 colors. To keep things simple fo rthe first one,w e set it to grab the forecolor and the backcolor to our groupBox, which is awlays changing, so we get random results every time, amking life exciting. we then set the angle of the gradient, this will determine if the colors fade left to right, top to bottom, in a diagonal, etc.
the second one, lgb, is exactly the same, only we use Randy to determine the color, so we come up with a completely seperate random color from the others, and theoretically have enough contrast to read what we typed.
Everything else works the same, so run your program (ctrl-f5), type something, and now look at the results. much more fun.
Vodstok
12-26-2006, 06:53 AM
Now, i will address one last concept today: The "if/else" statement. Notice if you run this program, and click the Make image button with no text, you get a background, but no words. But we want words, right? so add this:
private void btnImage_Click(object sender, EventArgs e)
{
if (tbImage.Text.Length > 0)
{
Bitmap bm = new Bitmap(300, 300, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bm);
Rectangle r = new Rectangle(0, 0, 300, 300);
//g.FillRectangle(new SolidBrush(ColorRed), r);
g.FillRectangle(new LinearGradientBrush(new Rectangle(0, 0, 300, 300), groupBox1.ForeColor, groupBox1.BackColor, 180), r);
//SolidBrush sb = new SolidBrush(Color.Black);
LinearGradientBrush lgb = new LinearGradientBrush(new Rectangle(0, 0, 300, 300), Randy, Randy, 90);
//g.DrawString(tbImage.Text, new Font(FontFamily.GenericSansSerif,12), sb, 10, 10);
g.DrawString(tbImage.Text, new Font(FontFamily.GenericSansSerif,12,FontStyle.Bold ), lgb, 10, 10);
g.SmoothingMode = SmoothingMode.AntiAlias;
string path = @"c:\";
bm.Save(path + "mine.jpg", ImageFormat.Jpeg);
}
else
{
MessageBox.Show("You have no words!");
}
}
what the new lines say is this: if the length of the text inour textbox is greater than zero (IE, it's not empty), run as usual. BUT (that is where "else" comes in) if there is no text, show a MessageBox that says "You have no words !", and do nothing else. This prevents any boring, no worded images. You could just as easily delete :
else
{
MessageBox.Show("You have no words!");
}
with no ill effects. It wont say or do anything if there is no text, it will just sit there until you type something into the box.
Post your best pics up here, i am curious to see what you guys do. :)
Vodstok
01-03-2007, 09:41 AM
Figured i would drag this guy up in case anyone is interested
made with the above program:
http://scaredyet.org/mine.jpg