Monday, June 29, 2009

Win32 Api Calls from C#

Here I am demonstrating opening and closing the CD Rom Drive using the win32 api with c#.
This was one of my favourite progam in VB era and so I thought of migrating it to C#.
mciSendString encapsulates the Media Control Interface developed by Microsoft and IBM for controlling the peripherals connected to Windows.

It's better to encapsulate the Win32 api inside a class library. So from the Windows Forms Application add a class library.

using System.Runtime.InteropServices;

namespace OpenCDWindow
{
class OpenCDDoor
{
[DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
public static extern void mciSendStringA(string lpstrCommand,
string lpstrReturnString, long uReturnLength, long hwndCallback);
}
}


Back in the windows forms you can call the win32 api that you have declared in the class.

string rt = "";
private void btnOpen_Click(object sender, EventArgs e)
{
OpenCDDoor.mciSendStringA("set CDAudio door open", rt, 127, 0);
}
private void btnClose_Click(object sender, EventArgs e)
{
OpenCDDoor.mciSendStringA("set CDAudio door closed", rt, 127, 0);
}


VB 6
Module
Public Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long

Form
Private Sub CmdClose_Click()
mciSendString "set CDAudio door closed", returnstring, 1, 0
End Sub

Private Sub CmdOpen_Click()
mciSendString "set CDAudio door open", returnstring, 1, 0
End Sub

AnimateWindow Win32 Api
Now we will take up a slightly more complex api which takes a few constatnts.
The AnimateWindow function enables you to produce special effects.
using System.Runtime.InteropServices;

const uint AW_HOR_NEGATIVE = 2;
const uint AW_VER_POSITIVE = 4;
const uint AW_HIDE = 0x10000;


[DllImport("User32.dll")]
static extern bool AnimateWindow(IntPtr hWnd, UInt32 time, UInt32 flags);

private void btnAnimate_Click(object sender, EventArgs e)
{
AnimateWindow(this.Handle, 1000, AW_VER_POSITIVE AW_HOR_NEGATIVE AW_HIDE);
}

WPF Treeview

TreeView is used for displaying hierarchical data. Individual items in a treeview is called TreeViewItem. Here I am declaratively creating a TreeView.




Output





Constructing a treeview with code
private void Window_Loaded(object sender, RoutedEventArgs e)
{
TreeViewItem tvwIndia = new TreeViewItem();
tvwIndia.Header = "India";

treeView1.Items.Add(tvwIndia);

TreeViewItem tvwKerala = new TreeViewItem();
tvwKerala.Header = "Kerala";
tvwIndia.Items.Add(tvwKerala);

TreeViewItem tvwKochi = new TreeViewItem();
tvwKochi.Header = "Kochi";
tvwKerala.Items.Add(tvwKochi);
}