How to get Windows explorer’s position using .net?

85 Views Asked by At

I am developing an application which triggers when there is a windows explorer window in foreground. My application triggers a window (form) which will be placed on screen near the opened windows explorer (Planning to keep it just below the search option).

But I am not getting anything to get the window position of foreground "windows explorer" window.

Is there any way to read the position of current foreground “Windows Explorer” window using .net?

1

There are 1 best solutions below

0
Alvimar On BEST ANSWER

You can do this by using unmanaged code.

Create a class:

    class RectMethods
    {
        // http://msdn.microsoft.com/en-us/library/ms633519(VS.85).aspx
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);

        // http://msdn.microsoft.com/en-us/library/a5ch4fda(VS.80).aspx
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
    }

Then, identify the explorer process to pick up your handle, and take the coordinates and the size of the window, and from there you can do what you want:

            var processes = System.Diagnostics.Process.GetProcesses();
            foreach (var process in processes)
            {
                if (process.ProcessName == "explorer")
                {
                    var hWnd = process.Handle;
                    RectMethods.RECT rect = new RectMethods.RECT();
                    if (RectMethods.GetWindowRect(hWnd, ref rect))
                    {
                        Size size = new Size(rect.Right - rect.Left,
                                 rect.Bottom - rect.Top);
                    }
                }
            }

Set 'Allow unsafe code' on Properties/Build...