Add Your Control On Top Another Application – Part 2 (Win32)

09/05/2010

Add Your Control On Top Another Application – Part 2 (Win32)image

In my previous post Add Your Control On Top Another Application – Part 1 (Win32) I’ve showed how to obtain window handle from process.

Now I can assume that we have the window handle (If not read Part 1), now we need to get TitleBarInfo fro the TargetWindow, Using that data we can get the position of the window and more.

 Download Project

Step 1: Add GetTitleBarInfo and GetLastError

Using GettitleBarInfo will allow us to get information from the Target application.

[return: MarshalAs(UnmanagedType.Bool)]

[DllImport("user32.dll")]

internal static extern bool GetTitleBarInfo(IntPtr hwnd, ref TITLEBARINFO pti);

 

//GetLastError- retrieves the last system error.

[DllImport("coredll.dll", SetLastError = true)]

internal static extern Int32 GetLastError();

 

Step 2: Add TitleBarInfo & RECT Properties

Before we can use GetTitleBarInfo let’s add the following properties to the NativeMethods class.

[StructLayout(LayoutKind.Sequential)]

internal struct TITLEBARINFO

{

    public const int CCHILDREN_TITLEBAR = 5;

    public uint cbSize; //Specifies the size, in bytes, of the structure.

    //The caller must set this to sizeof(TITLEBARINFO).

 

    public RECT rcTitleBar; //Pointer to a RECT structure that receives the

    //coordinates of the title bar. These coordinates include all title-bar elements

    //except the window menu.

 

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]

 

    //Add reference for System.Windows.Forms

    public AccessibleStates[] rgstate;

    //0    The title bar itself.

    //1    Reserved.

    //2    Minimize button.

    //3    Maximize button.

    //4    Help button.

    //5    Close button.

}

 

[StructLayout(LayoutKind.Sequential)]

internal struct RECT

{

    internal int left;

    internal int top;

    internal int right;

    internal int bottom;

}

Step 3: Add GetWindowPosition

Into the Helpers class add GetWindowPosition (below), GetWindowPosition first will initialize TITLEBARINFO (Make sure you set the sbSize) than use GetTitleBarInfo to get the TitleBar position on the screen.

public static WinPosition GetWindowPosition(IntPtr wnd)

{

    NativeMethods.TITLEBARINFO pti = new NativeMethods.TITLEBARINFO();

 

    pti.cbSize = (uint)Marshal.SizeOf(pti);//Specifies the size, in bytes, of the structure.

    //The caller must set this to sizeof(TITLEBARINFO).

 

    bool result = NativeMethods.GetTitleBarInfo(wnd, ref pti);

 

    WinPosition winpos;

    if (result)

        winpos = new WinPosition(pti);

    else

        winpos = new WinPosition();

 

    return winpos;

}

 

Download Project

Enjoy

Add comment
facebook linkedin twitter email

Leave a Reply