Disable "X" Close Button On Your Windows Form Application

12. December 2010 07:55

C# Code Snippets 

Recently, someone on MSDN forums asked this question on how to disable the "X" a.k.a. close button in his windows form application so the user is forced to close the application from the cancel button on the form and not from the close button. He wanted this for his application which requires registration first before a user can start using his application.

I don't know the answer so I bing arond a bit and find a solution posted by someone though I don't have the name but it worked like a charm....!!

We need some interoperability to do this, therefore get the namespace System.Runtime.InteropServices
Code:

private const int MF_BYPOSITION = 0x400;
[DllImport("User32")]
private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
[DllImport("User32")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("User32")]
private static extern int GetMenuItemCount(IntPtr hWnd);

Below code goes to the load event of your form:

IntPtr hMenu = GetSystemMenu(this.Handle, false);
int menuItemCount = GetMenuItemCount(hMenu);
RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);

Time to press 'F5'....and the close button is now disabled on the form.

Download: CloseButton.zip (43.08 kb)

 No Rating

A Time Wrapper Class in C#

30. November 2010 13:27

C# Code Snippets 

I was just surfing the net in search for some fundoo tutorial on WPF and by chance (I don't meant to visit that site), I get this class which I feel is pretty helpful. A simple wrapper class to conver time. the class allows you to convert:

  1. To Days
  2. To Hours
  3. To Minutes
  4. To Seconds
  5. To MilliSeconds

This can be pretty usefull. The class is as follows:

 

using System;

public static class TimeSpanUtil
{
    #region To days
    public static double ConvertMillisecondsToDays(double milliseconds)
    {
        return TimeSpan.FromMilliseconds(milliseconds).TotalDays;
    }

    public static double ConvertSecondsToDays(double seconds)
    {
        return TimeSpan.FromSeconds(seconds).TotalDays;
    }

    public static double ConvertMinutesToDays(double minutes)
    {
        return TimeSpan.FromMinutes(minutes).TotalDays;
    }

    public static double ConvertHoursToDays(double hours)
    {
        return TimeSpan.FromHours(hours).TotalDays;
    }
    #endregion

    #region To hours
    public static double ConvertMillisecondsToHours(double milliseconds)
    {
        return TimeSpan.FromMilliseconds(milliseconds).TotalHours;
    }

    public static double ConvertSecondsToHours(double seconds)
    {
        return TimeSpan.FromSeconds(seconds).TotalHours;
    }

    public static double ConvertMinutesToHours(double minutes)
    {
        return TimeSpan.FromMinutes(minutes).TotalHours;
    }

    public static double ConvertDaysToHours(double days)
    {
        return TimeSpan.FromHours(days).TotalHours;
    }
    #endregion

    #region To minutes
    public static double ConvertMillisecondsToMinutes(double milliseconds)
    {
        return TimeSpan.FromMilliseconds(milliseconds).TotalMinutes;
    }

    public static double ConvertSecondsToMinutes(double seconds)
    {
        return TimeSpan.FromSeconds(seconds).TotalMinutes;
    }

    public static double ConvertHoursToMinutes(double hours)
    {
        return TimeSpan.FromHours(hours).TotalMinutes;
    }

    public static double ConvertDaysToMinutes(double days)
    {
        return TimeSpan.FromDays(days).TotalMinutes;
    }
    #endregion

    #region To seconds
    public static double ConvertMillisecondsToSeconds(double milliseconds)
    {
        return TimeSpan.FromMilliseconds(milliseconds).TotalSeconds;
    }

    public static double ConvertMinutesToSeconds(double minutes)
    {
        return TimeSpan.FromMinutes(minutes).TotalSeconds;
    }

    public static double ConvertHoursToSeconds(double hours)
    {
        return TimeSpan.FromHours(hours).TotalSeconds;
    }

    public static double ConvertDaysToSeconds(double days)
    {
        return TimeSpan.FromDays(days).TotalSeconds;
    }
    #endregion

    #region To milliseconds
    public static double ConvertSecondsToMilliseconds(double seconds)
    {
        return TimeSpan.FromSeconds(seconds).TotalMilliseconds;
    }

    public static double ConvertMinutesToMilliseconds(double minutes)
    {
        return TimeSpan.FromMinutes(minutes).TotalMilliseconds;
    }

    public static double ConvertHoursToMilliseconds(double hours)
    {
        return TimeSpan.FromHours(hours).TotalMilliseconds;
    }

    public static double ConvertDaysToMilliseconds(double days)
    {
        return TimeSpan.FromDays(days).TotalMilliseconds;
    }
    #endregion
}
Currently rated 5.0 by 1 person

URL Routing With ASP.NET 4 - Web Forms

26. June 2010 18:38

.NET Framework ASP.NET C# 

URL Routing was first introduced in .NET framework 3.5 SP1 but MVC has built-in and works pretty decently to create SEO friendly URL and prevents URL hacking. ASP.NET 4.0 is now introduced with a new feature called URL routing with web forms. URL routing help developers to create short and friendly URLs which enhance search engine page ranking. There are few other ways to create short friendly URLs like URLrewriter.net extension or if you have a physical access to IIS you can have installed URL Rewriter extension for IIS 7 to create short friendly URLs. Hey! not everyone has access to IIS!! So if you don't have the access then also you can re-write the URLs using this new feature in ASP.NET 4.0. 

One thing I would like to mention is that when you create a new ASP.NET web application in Visual Studio 2010, it won't show up with a blank page, but instead build a full applicaton with sample pages with a pretty good design. As you see below I haven't design this page..actually this is a default template when you create a new ASP.NET web application. What I have done here is just put a text box to enter contact ID and a button to get the details from the Adventure Works sample database.

 

This is a pretty simple interface and now we take a look at some internal work of this web application. My primary focus is on having simple URLs for my application for better search engine optimizations. This application has two main pages apart from the about and other pages that added to the project through the template. The Default.aspx is the main page where we have a field which allow the user to enter the contact ID for the person he want to search. The other page which handles the request and show the details of the contact person is called View.aspx. But this is a really tricky part from a user's perspective as a user will never see this page on the browser address bar while navigating a website. Check the View.aspx design code and check the <asp:SqlDatasource> tags and notice the SelectParameter tag. As I am using a select query with a parameter to populate the grid, the SelectParameter tag further uses <asp:RouteParameter> with route name and route key.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" 
        SelectCommand="select Title,FirstName,MiddleName,LastName, EmailAddress from Person.Contact where ContactID=@id">
        <SelectParameters>
            <asp:RouteParameter Name="id" RouteKey="id" />
        </SelectParameters>
    </asp:SqlDataSource>

OK! Let's start up what we have on the Default.aspx page. This is the default page and a user will see this page first. Write the below code on the button to redirect the request to route handler. Here I have used a Regex expression to validate if the user enters a numeric ID and not any alphanumeric or alphabet. This check is just a workaround, I recommend you to use a better validation technique.

if((Regex.IsMatch(txt_pid.Text.Trim(), @"\d+")) == true)
{
          Response.RedirectToRoute("Persons-Details",
          new { id = txt_pid.Text });
}

So does this URL make any sense? Not at this moment but surely it will after if you have registered your routes in the Global.asax file. My Global.asax file has a method called void RegisterRoutes(RouteCollection Route)

void RegisterRoutes(RouteCollection routes)
{
       RouteTable.Routes.MapPageRoute("Persons-Details",
         "Person/{id}", 
         "~/View.aspx");
}

The method MapPageRoute accepts some parameters. The first parameter - "Person-Details" you see is the name of the Route which can be any thing you like. The second parameter - "Person/{id}" is the URL which we have generated. In short this is the URL which is visible to the user and outside world, what is happening internally only a developer knows!. The third parameter - "~/View.aspx" is the physical file which actually process the request and return it to the second parameter. The second parameter is the route URL and you can name it what you like except the parameter you are passing, just make sure you use the same parameter name everywhere. In the method void RegisterRoutes(RouteCollection Route) you can register number of route handlers in a single go under void Application_Start method in the Global.asax file.

void Application_Start(object sender, EventArgs e){
// Code that runs on application startup
RegisterRoutes(RouteTable.Routes);
}

Once you registered the routes in the Global.asax file, you are done. Time to press F5 and see the action. On the default page enter the ID and hit the Get Details button. The page rendered in front of you / user will be having a clean tidy URL.

 

 Download: ASP.NET4URLRouting.zip (175.58 kb)

Currently rated 5.0 by 1 person

Windows 7 Logon Screen Changer

29. May 2010 22:42

C# Projects Utils Windows 

Recently I was reading an article on some Windows 7 forums on how to change Windows Logon Background. There are manual steps which helps me to change the longon background, but its tedious if I have to do it manually everytime. So I decided to make a tool which can do it for me. 

I start up a new project in Visual Studio 2010 and create a new windows application. I am not writing about how I did it, I am just giving away this tool for use. Just Browse and click Change Logon Screen and you are done.

Press WIN+L to lock your computer and check your new logon screen. There is only one limitation, you cannot select an image which is larger than 256KB.

I will be uploading the complete source code at codeplex shortly. So keep an eye on the update.

Download: Win7 LogonScreenChanger.zip (49.21 kb)

Source Code: Win7LogonScreenChanger.zip (139.44 kb)

Currently rated 1.0 by 2 people

How To Build UAC Compatible Application In .NET

23. May 2010 21:01

C# Utils Visual Studio Windows 

We all know about a feature called User Account Control (UAC) which introduced with the launch of Windows Vista. By default, UAC is enabled and provides users a better and safer computing experience, but most of the users find it irritating when the UAC prompts everytime they try to run a program. Disabling UAC is not recommended at all.

With UAC enabled programmers find it difficult to access some of the locations on the local drive. Programatically you cannot write or create a file or directory in root partition, inside Program Files, System32 folder and some other locations. Recently I ran into a same problem where I have to access System32 folder, create new folders and copy files from one location on my system to this folder. With UAC disabled this is pretty easy, no security settings and no runtime errors or exceptions. Usually you cannot ask the users to disable UAC and then use the application, so therefore I made my application compatible with UAC and YES!!! you will be prompted with the confirmation box to run the application with administrator privileges. In Windows Vista and Windows 7, even if you are an administrator of your machine you do not have the complete access to resources even if you are an administrator. So in order to make your application run with full administrator rights follow the steps below. This will work the same if you run your application with "Run as Administrator" option which you see when you right-click the application.

Create a new application in Visual Studio. Right-click project and add a new item.

From the Add New Item box select Application Manifest File.

In the manifest file un-comment the following line:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Build your applicaton....and when the build is complete you will see the security shield icon accompanying your application icon. A dialogue box appear in front of the user to run the application with full administrative privileges.

Currently rated 4.5 by 2 people