1

I am writing a console application. it has to do the following

  1. I'll place(pin) EXE of this application in Task-bar of the window.

  2. I'll open windows explorer or there may be already many opened windows before.

  3. I'll select a window where I want to create a folder (folder hierarchy)

  4. I'll click on the icon from Task-bar of my EXE pinned in step 1.

I have tried following code.

It is working when I am scheduling it by using windows scheduler. after every 5 minutes a new folder will be created in the topmost window.

However when I am trying with executing exe after pinning it to taskbar, it is not working..

Please let me know if there is any solution.

NOTE - Helpful if you tell me how to create a new option of Create New Custom Folder after right click

using System;
using System.Text;

namespace CreateNewFolders
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // get the active window
                IntPtr handle = GetForegroundWindow();

                // Required ref: SHDocVw (Microsoft Internet Controls COM Object) - C:\Windows\system32\ShDocVw.dll
                SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();

                // loop through all windows
                foreach (SHDocVw.InternetExplorer window in shellWindows)
                {
                    Console.WriteLine(((int)handle).ToString());
                    Console.WriteLine(window.HWND.ToString());
                    if (window.HWND == (int)handle)
                    {
                        // Required ref: Shell32 - C:\Windows\system32\Shell32.dll
                        var shellWindow = window.Document as Shell32.IShellFolderViewDual2;

                        // will be null if you are in Internet Explorer for example
                        if (shellWindow != null)
                        {
                            // Item without an index returns the current object
                            var currentFolder = shellWindow.Folder.Items().Item();

                            // special folder - use window title
                            // for some reason on "Desktop" gives null
                            if (currentFolder == null || currentFolder.Path.StartsWith("::"))
                            {
                                // Get window title instead
                                const int nChars = 256;
                                StringBuilder Buff = new StringBuilder(nChars);
                                //if (GetWindowText(handle, Buff, nChars) > 0)
                                //{
                                //    return Buff.ToString();
                                //}
                            }
                            else
                            {

                                System.IO.Directory.CreateDirectory(currentFolder.Path + "//NewFolder//Db_Scripts");
                                System.IO.Directory.CreateDirectory(currentFolder.Path + "//NewFolder//Documents");
                                System.IO.Directory.CreateDirectory(currentFolder.Path + "//NewFolder//SourceCode");
                                // return currentFolder.Path;
                            }
                        }

                        break;
                    }
                }


            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
                Console.Read();
            }
            //Console.Read();
        }
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

    }
}

References to be added C:/windows/system32/Shell32 and Microsoft Internet Controls from COM.

captainsac
  • 2,484
  • 3
  • 27
  • 48
  • Do it with autohotkey, it is more simple, and you can create a hotkey for executing an action. – IamK Dec 13 '16 at 11:29
  • @C1sc0 sorry. do not have permission to use external tools – captainsac Dec 13 '16 at 11:36
  • Maybe it looses the focus when you clik on the taskbar, you can make an autohotkey like application for yourself (http://www.pinvoke.net/default.aspx/user32/SetWindowsHookEx.html) or place you tiny application on the context menu (just one line need to be added in the registry) – IamK Dec 13 '16 at 11:39
  • May be it is considering self console window as topmost window. but why it is running properly through a scheduler? – captainsac Dec 13 '16 at 11:43
  • Maybe try to find the z position http://stackoverflow.com/questions/825595/how-to-get-the-z-order-in-windows – Slai Dec 13 '16 at 11:49
  • 1
    Try simulate an Alt+Tab before you run your applicaiton logic `SendKeys.Send("%{Tab}")` this changes back to your last active window. – IamK Dec 13 '16 at 11:49
  • 1
    A better solution would be to just pop open a folder selection dialog and let the user pick the place to create the new folder, why do you need to muck around with Explorer windows? – Lasse V. Karlsen Dec 13 '16 at 12:14

1 Answers1

1

This code works for me, just 2 lines added. Before it executes changes back the last accessed window.

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace lastActiveWindow
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // New lines.. 
            SendKeys.SendWait("%{Tab}"); 
            Thread.Sleep(500);
            try
            {
                // get the active window
                var handle = GetForegroundWindow();

                // Required ref: SHDocVw (Microsoft Internet Controls COM Object) - C:\Windows\system32\ShDocVw.dll
                SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();

                // loop through all windows
                foreach (SHDocVw.InternetExplorer window in shellWindows)
                {
                    Console.WriteLine(((int) handle).ToString());
                    Console.WriteLine(window.HWND.ToString());
                    if (window.HWND == (int) handle)
                    {
                        // Required ref: Shell32 - C:\Windows\system32\Shell32.dll
                        var shellWindow = window.Document as Shell32.IShellFolderViewDual2;

                        // will be null if you are in Internet Explorer for example
                        if (shellWindow != null)
                        {
                            // Item without an index returns the current object
                            var currentFolder = shellWindow.Folder.Items().Item();

                            // special folder - use window title
                            // for some reason on "Desktop" gives null
                            if (currentFolder == null || currentFolder.Path.StartsWith("::"))
                            {
                                // Get window title instead
                                const int nChars = 256;
                                var Buff = new StringBuilder(nChars);
                                //if (GetWindowText(handle, Buff, nChars) > 0)
                                //{
                                //    return Buff.ToString();
                                //}
                            }
                            else
                            {
                                Directory.CreateDirectory(currentFolder.Path + "//NewFolder//Db_Scripts");
                                Directory.CreateDirectory(currentFolder.Path + "//NewFolder//Documents");
                                Directory.CreateDirectory(currentFolder.Path + "//NewFolder//SourceCode");
                                // return currentFolder.Path;
                            }
                        }

                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
                Console.Read();
            }
            //Console.Read();
        }

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
    }
}
IamK
  • 2,753
  • 5
  • 30
  • 39