Monday 25 November 2013

Fun with Win 32 API

Are you looking for fun with application running on your windows OS??? . So WinAPI is a way by which you can get control over applications and their windows. Believe me you can do lot of fun, like minimize a window from another application made by you. You can close notepad from another application.

Win 32 API is combination of mainly 3 DLL’s They Are

User32.dll - handles user interface stuff ,Like UI windows and functionality.

Kernel32.dll - file operations, memory management .

Gdi32.dll - involved in graphical .

Let’s start with Example: Let us suppose I want to close or minimize all window open in Desktop

Step 1: Use Name space “using System.Runtime.InteropServices;”

Step2: Import DLL’s declaring methods of corresponding like this.

clip_image002

For more details about different functions, Please visit this link: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx.

Step3: call method in your app where ever required

clip_image004

Full code for minimizing all open window and undo the same in C#:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace WindowsAPI_C_SHARP

{

public partial class Form1 : Form

{

//Importing DLL's

[DllImport("User32.dll")]

public static extern Int32 FindWindow(String lpClassName, String lpWindowName);

[DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true)]

static extern IntPtr SendMessage(Int32 hWnd, Int32 Msg, int wParam, IntPtr lParam);

int flag = 0;

public Form1()

{

InitializeComponent();

}

private void btn_minimize_Click(object sender, EventArgs e)

{

if(flag==0)

{

minimise_All_open_window();

flag = 1;

}

else

{

undo_minimise_All_open_window();

flag = 0;

}

}

void minimise_All_open_window()

{

const int WM_COMMAND = 0x111;

const int MIN_ALL = 419;

//const int MIN_ALL_UNDO = 416;

Int32 lHwnd = FindWindow("Shell_TrayWnd", null);

SendMessage(lHwnd, WM_COMMAND, MIN_ALL, IntPtr.Zero);

}

void undo_minimise_All_open_window()

{

const int WM_COMMAND = 0x111;

//const int MIN_ALL = 419;

const int MIN_ALL_UNDO = 416;

Int32 lHwnd = FindWindow("Shell_TrayWnd", null);

SendMessage(lHwnd, WM_COMMAND, MIN_ALL_UNDO, IntPtr.Zero);

}

}

}