Jump to content


Check out our Community Blogs

DeadLine

Member Since 31 May 2014
Offline Last Active Aug 30 2014 04:56 PM
-----

Topics I've Started

C# Tutorial - Drawing rectangles with the mouse

06 June 2014 - 01:02 PM

Introduction:

 

In this small tutorial I will teach you how you can draw a simple rectangle on your form with the mouse. The rectangle will be drawn dynamically as soon as the user presses any mouse button. This also means that if you move your mouse while pressing any of the mouse buttons, the rectangle will either get larger or smaller depending on which direction you moved your mouse to.

 

Tutorial:

 

Step 1:

 

We will be using a simple Windows Forms Application for this tutorial. The first thing you will need to do, is start a new project:

 

jbz9UKM.png

 

Step 2:

 

Right now, it's time to edit the design of the form a bit. Change the following properties:

  • Optional: [Backcolor : ActiveCaption]
  • DoubleBuffered : True
  • Optional: [FormBorderStyle : None]
  • Optional: [Opacity : 50% | (0.5 if you're doing it manually)]
  • Optional: [WindowState : Maximized]

DoubleBuffered will have to be set to true, to reduce or prevent flicker.

 

Step 3:

 

We will be 'using' the following references in our code:

using System;
using System.Drawing;
using System.Windows.Forms;

To keep track of wheter the user pressed a mouse button or not, we will need to add a variable to the code. We will also have to keep track of the start X and start Y position of the mouse. Add the following variables to our class:

private bool _canDraw;
private int _startX, _startY;

Now, it's time to add an event handler for the MouseDown event. You can find a list of all events in the Form Properties window:

E03ZMfg.png

 

Double click on this event and Visual Studio will generate an empty event handler for the MouseDown event. When any of the mouse buttons have been pressed, we want the system to know that it can now draw a rectangle and we also want to know the start position of the mouse. You can do all of this, by using the following code:

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            //The system is now allowed to draw rectangles
            _canDraw = true;
            //Initialize and keep track of the start position
            _startX = e.X;
            _startY = e.Y;
        }

We will also want the system to know when it is no longer allowed to draw rectangles. Since this should only happen when the mouse button has been released, we will be using the MouseUp event. Go back to the Designer and add the MouseUp event:

BlcADA2.png

 

All this event handler has to do, is set the _canDraw variable to false:

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            //The system is no longer allowed to draw rectangles
            _canDraw = false;
        }

We will need to add a Rectangle variable to the class:

private Rectangle _rect;

We want the system to draw the rectangle when a mouse button is down and when the user moves his or her mouse. To do this, we will need to add an event handler for the MouseMove event:

R5v2ckX.png

 

In the MouseMove event handler, we will want to initialize the _Rect variable and give it the correct values for x, y, width and height:

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            //If we are not allowed to draw, simply return and disregard the rest of the code
            if (!_canDraw) return;

            //The x-value of our rectangle should be the minimum between the start x-value and the current x-position
            int x = Math.Min(_startX, e.X);
            //The y-value of our rectangle should also be the minimum between the start y-value and current y-value
            int y = Math.Min(_startY, e.Y);

            //The width of our rectangle should be the maximum between the start x-position and current x-position minus
            //the minimum of start x-position and current x-position
            int width = Math.Max(_startX, e.X) - Math.Min(_startX, e.X);

            //For the hight value, it's basically the same thing as above, but now with the y-values:
            int height = Math.Max(_startY, e.Y) - Math.Min(_startY, e.Y);
            _rect = new Rectangle(x, y, width, height);
            //Refresh the form and draw the rectangle
            Refresh();
        }

With the code we have so far, we won't be able to actually draw the rectangle yet. We will need to override the OnPaint event in order to draw the rectangle. That is why we use 'Refresh();' in the code above. The OnPaint handler should look like this:

        protected override void OnPaint(PaintEventArgs e)
        {
            //Create a new 'pen' to draw our rectangle with, give it the color red and a width of 2
            using (Pen pen = new Pen(Color.Red, 2))
            {
                //Draw the rectangle on our form with the pen
                e.Graphics.DrawRectangle(pen, _rect);
            }
        }

Step 4:

 

Now it's time to spam the F5 key and actually test your code !

HKx6IKY.gif


Coffee & Smoking

01 June 2014 - 03:33 PM

Honestly, I can't be the only one who's addicted to coffee and cigarettes on this forum.

 

If you smoke, what kind of cigarettes do you smoke?

Also, what's your favorite coffee?

I prefer Kent & Douwe Egberts Senseo Coffee Pads.


DeadLine's Introduction

31 May 2014 - 01:56 PM

Hello everyone !

 

This is my introduction thread where I tell everyone a little bit about myself and how my life has been going so far.

Let's start from the beginning. I was born on october the 28th, 1994. My parents called me Alessandro and I'm not Italian, I'm actually Belgian :thumbup1: .

 

Life pretty much started for me when I was 14 years old. I was attending a biology class and we had to do some online research. The guy next to me suddenly started typing some weird thing in notepad and next thing you know, some kind of matrix batch window appeared ! I was amazed. I really wanted to know how he did that so he helped me learn batch. Nowadays, I don't really do anything in Batch anymore. I miss the old days when I think about it.

 

Anyway, I kinda wanted to created forms and good looking GUI's so I started doing some research on different languages to learn. I then stumbled upon VBScript. I started doing some things with VBScript but all I really wanted was to create GUI's which isn't really possible with VBScript. In this part of the story I'm 15 years old. I started looking for ways to create executable files and that's when I met my old friend Visual Basic. I was litterly so addicted to programming that my grades really went downhill. I decided that I should follow 'Information technology' (Dutch: 'Informaticabeheer') in school and so the next year, I did. When I was 16 years old I started programming in C# because the syntax looked better than VB.NET's.

 

Right now, I'm 19 years old and still attending school, this time however I'm trying to get a bachelor degree in computer sience.

 

I have learned the following things in the course of my life:

  • VB(.NET)
  • C#
  • VBScript
  • Delphi
  • Pascal
  • SQL
  • HTML
  • JS
  • CSS
  • Java
  • PHP

Oh also, I'm not proud of this but my home was raided by police once and all my computers were taken because of stupid things I did with my knowledge when i was younger.


C# Tutorial - Generating a unique hardware ID

31 May 2014 - 01:33 PM

Introduction:

 

In this tutorial, you will learn how to generate a unique hardware ID.

You might be wondering why you would want to generate a unique hardware ID. Well, you can do a lot with them:

  • You can use them for licensing purposes
  • Statistical purposes
  • ...

So, what exactly is a hardware ID (HWID) ?:

 

A hardware ID is a unique identifier generated from the serial numbers present in computer hardware. A hardware ID is not universal,  meaning that developers will usually use different methods to compose a hardware ID. In this tutorial I'll show you my preferred method of generating a hardware ID.

 

Sources:

 

(We will be using Sowkot Osman's code, but a modified version to improve performance)

 

Tutorial:

 

To generate a HWID, I generally grab the serials of CPU, motherboard, graphics card, BIOS, NIC and the disk. Then, I generate a MD5 hash using those variables and convert them to a hexadecimal value.

You will need the following in order to complete this tutorial:

  • Visual Studio or any other .NET (C#) IDE
  • A CPU
  • A motherboard
  • A graphics card
  • BIOS
  • a NIC
  • A hard drive

 

Step 1:

 

The first we will need to do is create a new console application or use an existing project:

 

Ir5UpYv.png

 

Step 2:

 

Now, it's time to add a reference to 'System.Management' to your project. You will need this reference in order to grab the serials of the computers hardware. You can do this by right clicking the references in the Solution Explorer and selecting 'Add reference...':

E8Ckrp5.pngNlleQ6c.png

Step 3:

 

We will be using the following references in the 'Using' list:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

The main method will look like this:

        static void Main()
        {
            Console.Write("Your HWID: ");
            Console.WriteLine(Value());
            Console.ReadLine();
        }

We will use the following code to generate a MD5 hash of our hardware serials:

        private static string GetHash(string s)
        {
            //Initialize a new MD5 Crypto Service Provider in order to generate a hash
            MD5 sec = new MD5CryptoServiceProvider();
            //Grab the bytes of the variable 's'
            byte[] bt = Encoding.ASCII.GetBytes(s);
            //Grab the Hexadecimal value of the MD5 hash
            return GetHexString(sec.ComputeHash(bt));
        }

In order to generate the hexadecimal string of the hash, you will need to add the following code:

        private static string GetHexString(IList<byte> bt)
        {
            string s = string.Empty;
            for (int i = 0; i < bt.Count; i++)
            {
                byte b = bt[i];
                int n = b;
                int n1 = n & 15;
                int n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s += ((char)(n2 - 10 + 'A')).ToString(CultureInfo.InvariantCulture);
                else
                    s += n2.ToString(CultureInfo.InvariantCulture);
                if (n1 > 9)
                    s += ((char)(n1 - 10 + 'A')).ToString(CultureInfo.InvariantCulture);
                else
                    s += n1.ToString(CultureInfo.InvariantCulture);
                if ((i + 1) != bt.Count && (i + 1) % 2 == 0) s += "-";
            }
            return s;
        }

The code above is used to generate the hexadecimal value of a string. For more information on Hexadecimal, please click here.

The code above will also add a '-' after every 4th character.

 

If you've done everything right, you should have a little error in your code. The method 'Value()' does not exist. This method will be used to grab the final hardware ID. Let's add it:

        private static string _fingerPrint = string.Empty;
        private static string Value()
        {
            //You don't need to generate the HWID again if it has already been generated. This is better for performance
            //Also, your HWID generally doesn't change when your computer is turned on but it can happen.
            //It's up to you if you want to keep generating a HWID or not if the function is called.
            if (string.IsNullOrEmpty(_fingerPrint))
            {
                _fingerPrint = GetHash("CPU >> " + CpuId() + "\nBIOS >> " + BiosId() + "\nBASE >> " + BaseId() + "\nDISK >> " + DiskId() + "\nVIDEO >> " + VideoId() + "\nMAC >> " + MacId());
            }
            return _fingerPrint;
        }

The code to get the hardware serials will be reused by different methods so first, we will create a new method for the code that's actually going to grab the required hardware serials:

        //Return a hardware identifier
        private static string Identifier(string wmiClass, string wmiProperty, string wmiMustBeTrue)
        {
            string result = "";
            System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementBaseObject mo in moc)
            {
                if (mo[wmiMustBeTrue].ToString() != "True") continue;
                //Only get the first one
                if (result != "") continue;
                try
                {
                    result = mo[wmiProperty].ToString();
                    break;
                }
                catch
                {
                }
            }
            return result;
        }
        //Return a hardware identifier
        private static string Identifier(string wmiClass, string wmiProperty)
        {
            string result = "";
            System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementBaseObject mo in moc)
            {
                //Only get the first one
                if (result != "") continue;
                try
                {
                    result = mo[wmiProperty].ToString();
                    break;
                }
                catch
                {
                }
            }
            return result;
        }

In order to grab the CPU ID, you will need to use the 'Identifier' code above with a couple of variables.

The code below will grab the UniqueID field from the processor but you don't need to grab all the different CPU ID's since this is very time consuming and some of them can fail on certain machines. That's why you need to add several more checks to actually get the appropriate processor id for the processor:

        private static string CpuId()
        {
            //Uses first CPU identifier available in order of preference
            //Don't get all identifiers, as it is very time consuming
            string retVal = Identifier("Win32_Processor", "UniqueId");
            if (retVal != "") return retVal;
            retVal = Identifier("Win32_Processor", "ProcessorId");
            if (retVal != "") return retVal;
            retVal = Identifier("Win32_Processor", "Name");
            if (retVal == "") //If no Name, use Manufacturer
            {
                retVal = Identifier("Win32_Processor", "Manufacturer");
            }
            //Add clock speed for extra security
            retVal += Identifier("Win32_Processor", "MaxClockSpeed");
            return retVal;
        }

For the BIOS ID, we will grab several variables such as the manufacturer, version, identification code, serial number etc.:

        //BIOS Identifier
        private static string BiosId()
        {
            return Identifier("Win32_BIOS", "Manufacturer") + Identifier("Win32_BIOS", "SMBIOSBIOSVersion") + Identifier("Win32_BIOS", "IdentificationCode") + Identifier("Win32_BIOS", "SerialNumber") + Identifier("Win32_BIOS", "ReleaseDate") + Identifier("Win32_BIOS", "Version");
        }

We could just get the serialnumber but using multiple variables will decrease the chances of machines having the same final HWID.

 

In order to get the hard drive information, you will need to use the following code:

        //Main physical hard drive ID
        private static string DiskId()
        {
            return Identifier("Win32_DiskDrive", "Model") + Identifier("Win32_DiskDrive", "Manufacturer") + Identifier("Win32_DiskDrive", "Signature") + Identifier("Win32_DiskDrive", "TotalHeads");
        } 

Again, we grab multiple variables in order to decrease the chances of machines having the same final HWID.

 

For the motherboard ID, we will grab the model, manufacturer, name and serialnumber.

This is the code to grab the motherboard information:

        //Motherboard ID
        private static string BaseId()
        {
            return Identifier("Win32_BaseBoard", "Model") + Identifier("Win32_BaseBoard", "Manufacturer") + Identifier("Win32_BaseBoard", "Name") + Identifier("Win32_BaseBoard", "SerialNumber");
        }

Right now, we still need the graphics card and NIC information. We will only get the driver version and name of the video card:

        //Primary video controller ID
        private static string VideoId()
        {
            return Identifier("Win32_VideoController", "DriverVersion") + Identifier("Win32_VideoController", "Name");
        }

We only want to grab the NIC mac address when the variable IPENABLED is true:

        //First enabled network card ID
        private static string MacId()
        {
            return Identifier("Win32_NetworkAdapterConfiguration", "MACAddress", "IPEnabled");
        }

Step 4:

 

Now it's time to actually run your program. Press F5 to run your application and try it out !

u5OrcVs.png


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download