Thursday, September 3, 2009

Using P/Invoke

  I want to show a good example showing the possibility of unmanaged code - we will hide the Start button and Taskbar. For the first time the possibility to use the Windows system functions in their programs, I learned when studying C#. If the C++ call is transparent to the programmer, then for C# is required to declare the desired function. In fact, the example does not have any practical purchase, but the example gives some idea of the organization Windows, and gives a more complete conception of the used functions. Let's start with the theory. First, the Start button, taskbar, system tray, and area of the clock - it is all windows. So, having access to this window, you can change habitual behavior of the interface element. Second - all these windows belong to specified classes. On behalf of the classes can be found descriptors required us windows to do experiments on them. Here are the names of classes:

  Shell_TrayWnd - Taskbar
  Button - Start Button
  TrayNotifyWnd - the notification area with icons and a clock
  TrayClockWClass - Clock

  Now on to functions. For our purposes, we need the function FindWindow, FindWindowEx and ShowWindow.

[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string ClassName, string WindowName);

[DllImport(
"user32.dll")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string className, string windowName);

[DllImport(
"user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

const int SW_HIDE = 0;
const int SW_SHOW = 5;


* This source code was highlighted with Source Code Highlighter.

  And then everything is easy. With the functions FindWindow and FindWindowEx on behalf of the class are required descriptors, which are then used in the function ShowWindow to hide or show the element.

bool show = false;

private void butHideTaskbar_Click(object sender, EventArgs e)
{
 
IntPtr taskBarWnd = FindWindow("Shell_TrayWnd", null);
 
IntPtr startWnd = FindWindow(taskBarWnd, IntPtr.Zero, "Button", null);

 
if (startWnd != IntPtr.Zero)
  ShowWindow(startWnd, show ? SW_SHOW : SW_HIDE);

 show = !show;
}

private void butHide_Click(object sender, EventArgs e)
{
 
IntPtr taskBarWnd = FindWindow("Shell_TrayWnd", null);
 
IntPtr tray = FindWindowEx(taskBarWnd, IntPtr.Zero, "TrayNotifyWnd", null);
 
IntPtr trayclock = FindWindowEx(tray, IntPtr.Zero, "TrayClockWClass", null);
 ShowWindow(trayclock, SW_HIDE);
}


* This source code was highlighted with Source Code Highlighter.

No comments:

Post a Comment