How to paint a Gradient Background for your Forms

Windows Forms

Have you ever felt that your Windows applications look a little boring and are missing that touch of visual style and creativity? I assume you have, so I’m going to show you how you can paint a gradient background for your Windows Forms. It might not sound like much but this goes a long way in making your interface more appealing to the end users of your application.

The .NET framework includes a class called System.Drawing.Drawing2D.LinearGradientBrush which is designed specifically for painting gradients. It accepts as parameters the coordinates of the object to paint, the two colours used to produce the gradient, and the angle of the gradient.

Now, let’s use this class to paint a gradient on our Windows Form.

We begin by overriding the form’s OnPaintBackground method like this:

protected override void OnPaintBackground(PaintEventArgs e)
{
}

This method will fire when the form is to be painted so it is the perfect event for us to paint our gradient in. Now that we have overridden the OnPaintBackground method we must create an instance of LinearGradientBrush and give it some parameters for our gradient. We must also paint the form using the Graphics‘ object FillRectangle method. The code for this is below:

protected override void OnPaintBackground(PaintEventArgs e)
{
    using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle,
                                                               Color.Gray,
                                                               Color.Black,
                                                               90F))
    {
        e.Graphics.FillRectangle(brush, this.ClientRectangle);
    }
}

[continue reading…]

16 comments

How to use a Master Page in ASP.NET

ASP.NET, Internet

When creating a website you will always have common sections which are repeated on every page throughout your whole site. For example headers and footers, a navigation bar, a side bar, etc. are all sections in your site which do not change depending on which page is being browsed. With a Master Page you only need to create these common sections once – ASP.NET will handle the rendering of them on every page automatically. This is a great advantage because you don’t have to copy identical code to every single page of your website.

So, how can you make use of these master pages? Let me show you.

Add a master page to your ASP.NET Web Application and call it Site.Master. If you view the source for this page you should see code similar to the below:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="MasterPageExample.Site" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

The magic of the master page is in the ContentPlaceHolder tags. ASP.NET will automatically render your content pages within these tags. What this means is that you can add any common HTML to your master page (around the ContentPlaceHolder tags) and when the page is rendered the content from your other pages will be wrapped in the master page.

To show you how this works let’s add a header and a footer to our master page Site.Master. The header will be “My Company Logo” and the footer will be “My Company Footer”.

<body>
    <form id="form1" runat="server">
    <h1>My Company Logo</h1>
    <br />
    <br />
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    <br />
    <br />
    <hr />
    <asp:Label ID="Label1" runat="server" Text="My Company Footer" Font-Size="XX-Small"></asp:Label>
    </form>
</body>

[continue reading…]

1 comment

Create a Worker Thread for your Windows Form in C#

Threads and Delegates, Windows Forms

When performing a relatively heavy operation on your Windows Form, what often happens is that your application’s UI will freeze until the heavy operation completes. This is usually unacceptable because your application’s end user will think it crashed and probably try to close it. To solve this problem you need to run your heavy operation on a separate thread from that of your UI. This way you will be able to run your operation while also keep the end user informed of the progress from the UI. In this article I will show you how to do just that.

First let’s create a form with a textbox which displays the progress of the heavy operation, and two buttons, one to start the process and one to stop it.

Next we need to create our heavy operation method. For this example let’s just create a loop which iterates for 1 million times.

private void HeavyOperation()
{
    // Example heavy operation
    for (int i = 0; i <= 999999; i++)
    {
    }
}

Now let's declare our thread and a boolean flag used to stop the heavy operation. We must use the System.Threading namespace to access the Thread class.

// Declare our worker thread
private Thread workerThread = null;

// Boolean flag used to stop the 
private bool stopProcess = false;

Next in the start button event handler method, we will initialise the thread and tell it to run the HeavyOperation method.

private void btnStart_Click(object sender, EventArgs e)
{
    this.stopProcess = false;

    // Initialise and start worker thread
    this.workerThread = new Thread(new ThreadStart(this.HeavyOperation));
    this.workerThread.Start();
}

Your code should be able to compile and run but you won't see anything happening because we still have to display the heavy operation's progress on the UI.

[continue reading…]

13 comments

What is an Overloaded Method?

Tutorials

Sometimes when programming, you might want to create a number of methods which internally have similar logic but accept different parameters. For example, an addition method called AddNumbers which, erm… adds numbers together, might accept two parameters of type int. But what if you want to add long values, or double values? You could create three separate methods called:

  • AddInt(int num1, int num2)
  • AddLong(long num1, long num2)
  • AddDouble(double num1, double num2)

But why create three methods with different names, therefore having to remember all three, when you can create three methods with the same name but different parameters?

With method overloading in C# you could instead create:

  • Add(int num1, int num2)
  • Add(long num1, long num2)
  • Add(double num1, double num2)

Note the method name is the same but the parameters are different. But this is a silly example for real-world use. Why would you want to create a method to add numbers together when you can simply use the ‘+’ keyword?

So let’s create a more useful example. Let’s create a method which searches for a string within another string.

[continue reading…]

1 comment

What Every Programmer Ought to Know About RSI

Books, Personal

If you are a programmer, or work in front of a pc all day, and have been doing it for a while, I’m sure you’ve either experienced RSI yourself, or else you know someone who has. RSI, or Repetitive Strain Injury, is not something to be taken lightly as it can become quite serious if nothing is done to prevent it from worsening. Trust me, I should know since I came quite close to serious RSI.

RSI symptoms are not always the same for everyone. Most people feel symptoms in their hands, but it can also affect the arms, shoulders, the neck, the chest and the back. RSI is more of a whole body problem then just a hand issue – at least that’s what it felt like for me.

My Experience

I’m a full-time programmer, and have been in the industry for over 7 years now. That might not seem like a whole lot but look at it this way – I work 8 hours a day, 5 days a week for approximately 52 weeks a year. If you do the math that adds up to 2,080 hours of programming a year. Now obviously you have to deduct paid leave and sick leave from that equation, but you also have to add weekends because I do spend a lot of them in front of the pc as well. Now, multiply that by 7 years and we have 14,560 hours spent in front of the pc typing and clicking. That’s quite a lot of typing and clicking. Now imagine doing that for your whole career – 30 or 40 years. I can assure you that you will experience some form of RSI if you do not take the necessary precautions. I did, after 6 years, and although it has gotten a lot better I am still experiencing certain problems.

It all started with a tingling sensation in my index and middle fingers on both hands. Although the strange thing was that this tingling occurred while I was driving and at night while sleeping. At first it never occurred when I was in front of the pc, which led me to believe it was not RSI.

So, just as most people do, I ignored it.

But then it started getting worse. After a few days it wasn’t just a tingling sensation any more. It had turned into light numbness of the thumb, index finger and middle finger. And it was starting to irritate me because I couldn’t do normal day to day stuff with my hands, such as reading a book or holding a fork and knife while having dinner. My hands would go numb for no reason.

So I went to see a doctor.

He examined my hands and concluded that it could be either Carpal Tunnel Syndrome, or a pinched nerve in my neck area. He suggested I adjust my seating position at work and also referred me to a specialist.

The next day I went to work and fiddled around with my chair until I set it up in what I thought was a more ergonomic position. I worked for a few days in that position but then started feeling pain in other places, more specifically my neck and chest. Apart from this my hands were still getting worse. I could no longer carry heavy items, not even a grocery bag. I would wake up at night with shooting pain in my arms and unable to move them due to numbness. At this point of my life RSI was a real problem.

[continue reading…]

0 comments