Archive

Archive for the ‘Win 32 API’ Category

How to disable Close button of Windows Forms Application

August 25th, 2010 Anuraj P No comments

We can disable the close button of a Windows Form in three ways

  1. Set controlbox property to false – It is most easy way to do this. But it also hides the Minimize and Maximize buttons.
  2. Using WIN32 API – Using Win32 API, we are getting the system menu and removes the close menu item using Remove menu item.
    Here is the Code.

    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);
    
    //In the Form load event
    IntPtr hMenu = GetSystemMenu(this.Handle, false);
    int menuItemCount = GetMenuItemCount(hMenu);
    RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);
    

    And here is the screenshot

    Using WIN32 API

    Using WIN32 API

  3. By Overriding the CreateParams property – The CreateParams property gets the required creation parameters when the control handle is created. By overriding the property we are removing the close button. You can get more information about CreateParams in MSDN
    Here is the code.

    private const int CS_CLOSE = 0x200;
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams parms = base.CreateParams;
            parms.ClassStyle |= CS_CLOSE;  //
            return parms;
        }
    }
    

    And here is the screenshot

    By Overriding CreateParams property

    By Overriding CreateParams property

    All of above three methods will work fine. But if you are using Windows 7 none of the above will work or OS will override all these.

    Windows 7 - Close Window

    Windows 7 - Close Window

Creating Wizard using Windows Forms

August 9th, 2010 Anuraj P No comments

In my first WinForms application, I have to create various wizard screens, I couldn’t find any ready made Controls for it from Microsoft. Then one of my colleague suggested a way to tweak it, like Add a Tab Control, Set the Alignment property to bottom and add a panel on top of the Tab Control, which contains Next / Previous / Cancel buttons. It was working fine. Few days back again I got the same situation for one of my personal project, and I thought about writing a control for the same. After doing some research I found a simple code snippet, which helps to hide the Tab Pages title in Runtime.

Here is the code, in this I am extending the Tab control and overriding the WndProc event.

protected override void WndProc(ref Message m)
{
    // Hide tabs by trapping the TCM_ADJUSTRECT message
    if (m.Msg == 0x1328 && !DesignMode)
    {
        m.Result = (IntPtr)1;
    }
    else
    {
        base.WndProc(ref m);
    }
}

You can find more details about TCM_ADJUSTRECT Message on MSDN.

Convert Image to Icon using C#

September 30th, 2009 Anuraj P 6 comments

Sometimes we will get nice Images from Web as Icons. But we can’t use these Images as application icons in .Net, because the .Net supports *.ico(Icon) format only. This code will convert an Image to Icon using C#. It is written .Net Framework 3.5, but it should work in .Net 2.0. It supports Images upto size 128×128. And supports various image formats(*.jpg,*.gif, *.png. *.bmp).

using System;
using System.Drawing;
using System.IO;

string fileName, newFileName;
fileName = "C:\Sample.jpg";
newFileName = Path.ChangeExtension(fileName, ".ico");
using (Bitmap bitmap = Image.FromFile(fileName, true) as Bitmap)
{
    using (Icon icon = Icon.FromHandle(bitmap.GetHicon()))
    {
        using (Stream imageFile = File.Create(newFileName))
        {
            icon.Save(imageFile);
            Console.WriteLine("Converted - {0}", newFileName);
        }
    }
}

Code it pretty self explanatory. Let me know if you have faced any issues.

Consuming a C++ DLL in C#

July 10th, 2009 Anuraj P No comments

While working on my current project, I had to use some low level I/O operations, but it was difficult using C#, and I got some C++ implementations. Then I thought of creating a DLL in C++ and use it in C#, but I didn’t get any code for the implementation. So I done some searching and I found a solution. It is not a complete solution, but it works :)

Creating a DLL using C++
For creating a DLL in C++, I was used cl.exe, which comes with .net framework. For the implementation I just wrote simple C++ file.(Simple.cpp)

#include <iostream>

extern "C" __declspec(dllexport) char* Hello();
char* Hello()
{
	return "Hello world";
}

I think this is pretty much clear.The extern “C” __declspec(dllexport) allows generate export names automatically. For more details :Exporting from a DLL Using __declspec(dllexport)(MSDN)

After creating this Simple.cpp file, go to Visual Studio Tools > Visual Studio 2008 Command Prompt. Go to the location where you have stored the Simple.cpp file and for compiling and linking C++ file you can use “cl.exe /LD Simple.cpp”.(For more details about cl.exe options checkout : Compiler Options Listed Alphabetically(MSDN) It will compile and Link, and gives a DLL as output.

Consuming a C++ library in C#
When I try to add the DLL by Add Reference, Visual Studio will not allows to add C++ library as Reference. So I tried it with Interop option, by using DLLImportAttribute.

[DllImport(@"D:\Simple.dll", EntryPoint = "Hello")]
public extern static string Hello();

Then you can call this function in C# like the following

private void button1_Click(object sender, EventArgs e)
{
            MessageBox.Show(Hello());
}

It will display a Messagebox with “Hello World”. Thats it you consumed a C++ DLL in C#.

Issue in the implementation

  1. I can’t use the DllImport function without the full location. To avoid this I tried to Register the DLL using RegSvr32.But I got some error from RegSvr like this.
  2. The module “D:\Simple.dll” was loaded but the entry-point DllRegisterServer was not found.

    Make sure that “D:\Simple.dll” is a valid DLL or OCX file and then try again.

I still exploring the things, I will update once I got the solution for this. Happy Coding :)

Disable autorun of USB disks

February 18th, 2009 Anuraj P 2 comments

In the last post I was implemented the USB detection, but the problem become more complex, because my USB stick contains some Autorun.inf file and when you plug the stick, it start executing some program, otherwise you need to cancel it explicity. The client need to avoid this. So I have to find some solution, where, I need to disable the autorun, when my program is running. Luckly, on the first search in google only, I got the solution.

Here is the implementation.

'API
Public QueryCancelAutoPlay As Integer = 0
Public Shared Function RegisterWindowMessage(ByVal strMessage As String) As Integer
'No implementation required.
End Function

'Modified implementation of WndProc() method

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If QueryCancelAutoPlay = 0 Then
QueryCancelAutoPlay = RegisterWindowMessage("QueryCancelAutoPlay")
End If

If m.Msg = WM_DEVICECHANGE Then
Select Case m.WParam
Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEARRIVAL
lblMessage.Text = "USB Inserted"
Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEREMOVECOMPLETE
lblMessage.Text = "USB Removed"
End Select
ElseIf m.Msg = QueryCancelAutoPlay Then
m.Result = CType(1, IntPtr)
Return
End If
MyBase.WndProc(m)
End Sub

I implemented it in C#, and I re-wrote it in VB.Net, and I didn’t tested it ;) If you are facing any issues, let me know.

How to detect USB insertion and removal in VB.Net

February 13th, 2009 Anuraj P 4 comments

Recently I moved to a Desktop application development team, where I have to look for the insertion of the USB. I need to read the contents of the USB drive and updates the application. I got a lot of solutions from Google to detect the USB insertion and removal. I am posting the easiest one I found, it is VB.Net, but I don’t think we can use it Class Libraries, and we may need to use the Windows Forms.

    Private WM_DEVICECHANGE As Integer = &H219

    Public Enum WM_DEVICECHANGE_WPPARAMS As Integer
        DBT_CONFIGCHANGECANCELED = &H19
        DBT_CONFIGCHANGED = &H18
        DBT_CUSTOMEVENT = &H8006
        DBT_DEVICEARRIVAL = &H8000
        DBT_DEVICEQUERYREMOVE = &H8001
        DBT_DEVICEQUERYREMOVEFAILED = &H8002
        DBT_DEVICEREMOVECOMPLETE = &H8004
        DBT_DEVICEREMOVEPENDING = &H8003
        DBT_DEVICETYPESPECIFIC = &H8005
        DBT_DEVNODES_CHANGED = &H7
        DBT_QUERYCHANGECONFIG = &H17
        DBT_USERDEFINED = &HFFFF
    End Enum

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = WM_DEVICECHANGE Then
            Select Case m.WParam
                Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEARRIVAL
                    lblMessage.Text = "USB Inserted"
                Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEREMOVECOMPLETE
                    lblMessage.Text = "USB Removed"
            End Select
        End If
        MyBase.WndProc(m)
    End Sub

The code is pretty clear; I am overriding the WndProc method. When a USB inserted or removed, Windows will send some message (WM_DEVICECHANGE) to all the applications. And the WParam property of that message will contains the details of the device event. The system broadcasts the DBT_DEVICEARRIVAL device event when a device or piece of media has been inserted and becomes available. The system broadcasts the DBT_DEVICEREMOVECOMPLETE device event when a device or piece of media has been physically removed.

Now I am looking into how can remove a USB programmatically.