Wednesday, September 29, 2010

C# Tutorial: Create a Custom ProgressBar [Custom Controls]

Here is the code

using System.Drawing.Drawing2D;
////////////////////////////////////////////////////////
label1.ForeColor = Color.Black;
this.ForeColor = SystemColors.Highlight; // Set the default color of the Pbar

protected float percent = 0.0f; // Protected because we don't want this to be accessed from the outside
// Create a Value property for the Pbar
public float Value
{
    get
    {
        return percent;
    }
    set
    {
        // Maintain the Value between 0 and 100
        if (value < 0) value = 0;
        else if (value > 100) value = 100;
        percent = value;
        label1.Text = value.ToString() + "%"; 
        // Redraw the Pbar every time the Value changes
        this.Invalidate(); 
    }
}
protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    Brush b = new SolidBrush(this.ForeColor); // Create a brush that will draw the background of the Pbar
    // Create a linear gradient that will be drawn over the background. FromArgb means you can use the Alpha value wich is the transparency
    LinearGradientBrush lb = new LinearGradientBrush(new Rectangle(0, 0, this.Width, this.Height), Color.FromArgb(255, Color.White), 

Color.FromArgb(50, Color.White), LinearGradientMode.ForwardDiagonal);     
    // Calculate how much has the Pbar to be filled for "x" %
    int width = (int)((percent / 100) * this.Width);
    e.Graphics.FillRectangle(b, 0, 0, width, this.Height);
    e.Graphics.FillRectangle(lb, 0, 0, width, this.Height);
    b.Dispose(); lb.Dispose(); 
}

/////////// Pbar_SizeChanged /////////////
// Maintain the label in the center of the Pbar
label1.Location = new Point(this.Width / 2 - 21 / 2 - 4, this.Height / 2 - 15 / 2);

Or download the solution

Monday, September 20, 2010

C# Tutorial: Keep Graphics on the Form after Minimize

Here is the code

// Declare a Bitmap object.
Bitmap image;

/////////////// Form1_Load /////////////////////////////
// Create a new Bitmap object(an image). Set the image to the size of pictureBox1.
image = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

//////////////// PictureBox1_Paint //////////////////
// Draw the image on the pictureBox1.
e.Graphics.DrawImage(image, 0, 0, image.Width, image.Height);

//////////////// Button "Draw my line" ////////////
// Create a graphic object from the image.
Graphics g = Graphics.FromImage(image);
// Draw a line on the image.
g.DrawLine(Pens.Red, 50, 50, 75, 200);
// Redraw pictureBox1.
pictureBox1.Invalidate();

Or download the solution

Friday, September 17, 2010

C# Tutorial: Capture Screen [Take Screenshots]

Here is the code

using System.Drawing.Imaging;
using System.Threading;

///////////////// Declarations ////////////////////////
ImageFormat img; Bitmap bt; Graphics screenShot;

///////////////////// Button1 /////////////////////////////
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    this.Hide();
    // This gives time to the Form to hide before it takes the screenshot. 500 miliseconds are enough.
    Thread.Sleep(500); 
    // Set the image to the size of the screen.
    bt = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
    // Creates the graphic object for the image (bt).    
    screenShot = Graphics.FromImage(bt);
    // Takes the screenshot.
    screenShot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, 

CopyPixelOperation.SourceCopy);
    switch (saveFileDialog1.FilterIndex)
    {
        case 0: img = ImageFormat.Bmp; break;
        case 1: img = ImageFormat.Png; break;
        case 2: img = ImageFormat.Jpeg; break;
    }
    // Saves the image.
    bt.Save(saveFileDialog1.FileName, img);
    // After the screenshot is taken the Form reappears.
    this.Show();
}

Or download the solution

Wednesday, September 15, 2010

C# Tutorial: Mail Sender [Send e-mails using C#]

Here is the code

///////////////// Button Send /////////////////
MailMessage mail = new MailMessage(from.Text, to.Text, subject.Text, body.Text);
// SmtpServer = smtp.company.com; Ex: Gmail - smtp.gmail.com | Yahoo - smtp.yahoo.com
SmtpClient client = new SmtpClient(smtp.Text);
// Port 587 is the preferred port for mail submission. Port 25 is widely abused by malware to spread worms and spam.
//  As a result, many ISPs are restricting its use. I tried to use it but it didn't work!
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential(username.Text, password.Text);
// Port 587 allows you to use a SSL Connection.
client.EnableSsl = true;
client.Send(mail);
MessageBox.Show("Mail Sent!", "Success", MessageBoxButtons.OK);

Or download the solution

Sunday, September 12, 2010

C# Tutorial: Create a Control while the Program is running

This is the code

Button btn = new Button();
///////////////////////////////////////////////////////

/////////// Button1_Click ////////////////
// Set the parent container of the button. In our case is the main form which is "this".
btn.Parent = this;
// The location where the button will be created.
btn.Location = new System.Drawing.Point(13, 81);
// The size of the button.
btn.Size = new System.Drawing.Size(60, 85);
// The Name of the button.
btn.Name = "btn1";
// The text that will appear on the button.
btn.Text = "My Button";

Or download the solution

Friday, September 10, 2010

C# Tutorial: Create a Simple Splash Screen [with ProgressBar]

Here is the code

////////////// Form1 //////////////////////////////////////
// We start Form2 on its own thread. By doing that we can run Form1 and Form2 in parallel.
Thread t = new Thread(new ThreadStart(SplashScreen));
t.Start();  
// Form1 is delayed by 5 sec so the SplashScreen has time to fully load its progressbar.
Thread.Sleep(5000);
// Add this after InitializeComponent();
// After Form1 is loaded the SplashScreen's thread is terminated.
t.Abort();

////////// SplashScreen Function /////////
Application.Run(new Form2());

//////// Form2 Timer //////////////////////////////
progressBar1.Increment(1);
if (progressBar1.Value == 100) timer1.Stop();

Or download the solution

More about Threads

Monday, September 6, 2010

C# Tutorial: Create a Simple Shutdown Manager #2 [usingSystem.Management]

Here is the code

string flags, time, oldtime;
/////////////////////////////////////

///////// Button "Start" ////////////
time = textBox1.Text;
switch (comboBox1.SelectedIndex)
{
    case 0: { flags = "1"; toolStripStatusLabel1.Text = "Windows will shut down in " + time + " seconds!"; } break;
    case 1: { flags = "2"; toolStripStatusLabel1.Text = "Windows will restart in " + time + " seconds!"; } break;
    case 2: { flags = "0"; toolStripStatusLabel1.Text = "Windows will log off in " + time + " seconds!"; } break;
}
timer1.Start();

//////// Shutdown Function //////////
public void Shutdown()
{
    ManagementBaseObject shutdown = null;
    ManagementClass win32 = new ManagementClass("Win32_OperatingSystem");
    win32.Get();
    // You can't shutdown without security privileges 
    win32.Scope.Options.EnablePrivileges = true;
    // 1 - Shutdown; 2 - Restart; 0 - Log Off; 4 - Forced Log Off; 5 - Forced Shutdown; 6 - Forced Restart; 8 - Power Off; 12 - Forced Power Off.
    ManagementBaseObject shutdownparam = win32.GetMethodParameters("Win32Shutdown");
    shutdownparam["Flags"] = flags;
    shutdownparam["Reserved"] = "0";
    foreach (ManagementObject mObj in win32.GetInstances())
    {
        shutdown = mObj.InvokeMethod("Win32Shutdown", shutdownparam, null);  
    }
}

///////// Button "Abort" ////////////
timer1.Stop(); toolStripStatusLabel1.Text = "Task Aborted";


//////// Timer //////////////////////
oldtime = time;
time = (Convert.ToInt32(time) - 1).ToString();
toolStripStatusLabel1.Text = toolStripStatusLabel1.Text.Replace(oldtime, time);
if (time == "0") { Shutdown(); timer1.Stop(); }

Or download the solution

Friday, September 3, 2010

C# Tutorial: Create a Simple Shutdown Manager

Here is the code

using System.Diagnostics;
///////////////////////////////////////////
String shutdown;

/////////// Start Button //////////////////
Process.Start("Shutdown", shutdown + " -t " + textBox1.Text + @" -c ""Windows is going to shut down!"""); // -t = time , -c = comments
timer1.Start(); label3.Text = textBox1.Text;
 
/////////// Abort Button //////////////////
Process.Start("Shutdown", "-a"); timer1.Stop(); // -a = abort

/// ComboBox_SelectedIndexChanged Event ///
switch (comboBox1.SelectedIndex)
{
    case 0: shutdown = "-s"; break; // -s = shutdown
    case 1: shutdown = "-r"; break; // -r = restart
    case 2: shutdown = "-l"; break; // -l = log off
}

/////////// Timer_Tick Event //////////////
label3.Text = (Convert.ToInt32(label3.Text) - 1).ToString();

// NOTE: Exiting the program will NOT abort the shutdown! You must press the "Abort" button before exit!
// If you forgot to abort the shutdown don't worry! Open Command Prompt and type in "shutdown -a" (without quotes)!

Or download the solution

Thursday, September 2, 2010

C# Tutorial: Searching words in a text and highlighting them

Here is the code

int index = 0; string temp = richTextBox1.Text; richTextBox1.Text = ""; richTextBox1.Text = temp;

while (index < richTextBox1.Text.LastIndexOf(textBox1.Text))
{
    // Searches the text in a RichTextBox control for a string within a range of text withing the control and with specific options applied to the search.
    richTextBox1.Find(textBox1.Text, index, richTextBox1.TextLength, RichTextBoxFinds.None);
    // Selection Color. This is added automatically when a match is found.
    richTextBox1.SelectionBackColor = Color.Yellow; 
    // After a match is found the index is increased so the search won't stop at the same match again. This makes possible to highlight same words at the same time.
    index = richTextBox1.Text.IndexOf(textBox1.Text, index) + 1; 
}

Or download the solution