Processing Ajax...

Title
Close Dialog

Message

Confirm
Close Dialog

Confirm
Close Dialog

Project Setup Opener

Description
I'm a software developer for construction machinery. When working on a project I like to have multiple Explorer Windows open which are related to the project. And of course I like to have them positioned over my multiple monitor setup.
So wrote this scripted function which allows to store a setup of open Explorer windows for a given parent window.
Use hotkey 'Alt + Ctrl + Win + Y' while the parent window is focused.
Both the paths and the positions of open explorer windows are stored for the current monitor configuration.
If later on the parent window is opened while the spacebar is pressed, the complete setup is restored.
Individual setups can be stored for different monitor configurations. If a setup does not exist for
the current monitor configuration, the script applies one of the existing ones and assures that
no window is outside the visible area.
You need to assign:
- 'Alt + Ctrl + Win + Y' as hotkey to run this scripted function
- A trigger for:
- 'Window created',
- 'Process Filename': 'C:\Windows\explorer.exe',
- 'Windows Class': 'CabinetWClass'
- 'Run Function': 'Project Setup Opener'
If you want to change the hotkey 'Alt + Ctrl + Win + Y', or want a different key than the spacebar to restore setups, make sure to adjust the strings 'KeyDownOpener', 'KeyDownOpener2' and 'KeyDownCreator' in the script to your choices.
See the comment section at the beginning of the script for details.
Language
C#.net
Minimum Version
Created By
Christian Treffler
Contributors
-
Date Created
Nov 23, 2021
Date Last Modified
Nov 23, 2021

Scripted Function (Macro) Code

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Drawing;
using System.Web;
using System.Linq;

// V1.0
// by: Christian Treffler
// 
// The function allows to store a setup of open Explorer windows for a given parent window.
// Use hotkey 'Alt + Ctrl + Win + Y' while the parent window is focused.
// Both the paths and the positions of these windows are stored for the current monitor configuration.
// If the parent window is opened while the spacebar is pressed, the complete setup is restored.
// Individual setups can be stored for different monitor configurations. If a setup does not exist for 
// the current monitor configuration, the script applies one of the existing ones and assures that
// no window is outside the visible area.
// A kind of recursion could occur, but is per default prevented in the code: 
// If one of the windows which are opened for a parent folder is itself a parent folder for a project setup,
// it would cause the respective setup to be executed, too.
// If you want to allow this recursion, set 'PreventRecursion' below to 'false'.
//
// You need to assign:
// - 'Alt + Ctrl + Win + Y' as hotkey to run this scripted function
// - A trigger for:
//   - 'Window created', 
//   - 'Process Filename': 'C:\Windows\explorer.exe', 
//   - 'Windows Class': 'CabinetWClass'
//   - 'Run Function': 'Project Setup Opener'
//
// If you want to change the hotkey 'Alt + Ctrl + Win + Y', or want a different key than the spacebar to 
// restore setups, make sure to adjust the strings 'KeyDownOpener', 'KeyDownOpener2' and 'KeyDownCreator' below to your choices

public static class DisplayFusionFunction
{
    // Virtual Key Codes: https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
    
    // When this key is pressed while opening an explorer window, 
    // the function will check, if a project setup exists and apply it
    private const string KeyDownOpener = "32"; 		// Spacebar 
    private const string KeyDownOpener2 = "18;32";   // Ctrl + Spacebar. This is for opening a folder with ctrl - doubleclick and space

    // When this hotkey combination is pressed, the function will store the current project setup
    // This string must be identical to the key combination used to start this function
    private const string KeyDownCreator = "17;18;89;91"; // Alt + Ctrl + Win + Y
	
	private const bool PreventRecursion = true; // Set to false, if recursion should be allowed
	private const int  BlockTime = 5000;        // Block recursion for <BlockTime> ms.
    
    private const bool ErrorMessages = false;	// Set to true for debugging Purposes

	public static void Run(IntPtr windowHandle)
	{
        try
        {
			ProjectSetups SavedSetups = null;
			string currPath = "";
			string currDirectory = "";
			string ProfileName = "";

            bool opener  =  BFS.Input.IsKeyDown(KeyDownOpener)
						 || BFS.Input.IsKeyDown(KeyDownOpener2); // Folder opened while Spacebar is pressed?
            bool creator = BFS.Input.IsKeyDown(KeyDownCreator);  // Started by Hotkey?
			
			ExplorerWindows.ErrorMessages = ErrorMessages;
						
            if (opener || creator)	// Standard initialization for all purposes
            {
                // Get all open Explorer windows and set relevant variables
				ExplorerWindows.InitExplorerHandler(windowHandle);
                currPath = ExplorerWindows.GetPath(windowHandle, true);	// Path to current folder which is the parent for the Project Setup 
				currDirectory = Path.GetFileName(currPath);				// Name of the current folder
							
				if(   BFS.Window.GetClass(windowHandle) == "CabinetWClass"
				  &&  currPath.Length > 0)
				{
					SavedSetups = LoadProjectSetups(currDirectory); 		// Check, if project setup exists (otherwise empty setup)
					
					// Get Resolution of all Monitors and create profile name
					Rectangle[] Monitors = BFS.Monitor.GetMonitorBounds(); 
					ProfileName = buildProfileName(Monitors);
				}
				else
				{
					opener  = false;
					creator = false;
				}
            }
            
            if (opener) 		// Apply Project Setup
            {
                if (PreventRecursion)
				{
					int timeblocked = BFS.ScriptSettings.ReadValueInt("PSO_TimeBlocked");
					int timenow = Environment.TickCount;
					
                    if (timeblocked > timenow) // System probably restarted, timeblocked is not valid
                    {
                        timeblocked = 0;
                    }
                    
					if (timeblocked + BlockTime > timenow)
					{
						opener = false;
					}
					else
					{
						BFS.ScriptSettings.WriteValueInt("PSO_TimeBlocked", timenow);
					}
				}
				
				if (    opener
                    &&  SavedSetups.HasSetups())
				{
					ProjectSetup loadedsetup = SavedSetups.GetSetup(ProfileName);
					
					// Open windows, if they are not already open
					foreach (KeyValuePair<string, Rectangle> window in loadedsetup.Prgrms) 
					{
						IntPtr handle = ExplorerWindows.GetHandle(window.Key, false);
						if (handle == IntPtr.Zero)
						{
							uint appid = BFS.Application.Start(HttpUtility.UrlDecode(window.Key, System.Text.Encoding.Default));
						}
					}
					
					bool allpresent = false;
					int  counter = 0;
					List <IntPtr> allwindows = null;
					
					// It seems that there is a considerable time between 'BFS.Application.Start' and the actual existence of the 
					// respective explorer window. In order to speed up, the delay time is cut short and we try several times until
					// all windows are present
					while ( (allpresent == false) && (counter < 10) )
					{
						BFS.General.ThreadWait(200);	// Allow all windows to open					
						
						allpresent = true;
						counter++;
						
						ExplorerWindows.InitExplorerHandler(windowHandle);
						allwindows = new List <IntPtr>();
						
						// Move the windows to their positions
						foreach (KeyValuePair<string, Rectangle> window in loadedsetup.Prgrms) 
						{
							IntPtr handle = ExplorerWindows.GetHandle(window.Key, true);
							if (handle != IntPtr.Zero)
							{
								allwindows.Add(handle);
								Rectangle rect = window.Value;
								BFS.Window.SetSizeAndLocation(handle, rect.Left, rect.Top, rect.Width, rect.Height);
							}
							else
							{
								allpresent = false;
							}
						}
					}
					
					BFS.General.ThreadWait(1000);	// Allow all windows to find their place					
					
					// Find windows which are not on a visible screen
					foreach (IntPtr handle in allwindows)
					{
						Rectangle WinRect = BFS.Window.GetBounds(handle);
						bool moveit = false; 
						uint monitorid = BFS.Monitor.GetMonitorIDByWindow(handle);
						if(monitorid == 0)	// Not on any monitor
						{
							moveit = true;
						}
						else
						{
							Rectangle IntersectSize = Rectangle.Intersect(WinRect, BFS.Monitor.GetMonitorBoundsByID(monitorid));
							if (IntersectSize.Width < 3 || IntersectSize.Height < 3) // Have a monitor, but barely visible
							{
								moveit = true;
							}
						}
						
						if(moveit)
						{
							BFS.DisplayFusion.RunFunctionWithWindowHandle("Move Window to Current Monitor", handle);
							BFS.Window.MoveToCentreMonitor(handle);
							BFS.Window.SetSize(handle, WinRect.Width, WinRect.Height);
						}
					}
				}
            }
            else if (creator)   // Save Project Setup
            {
				ProjectSetup newsetup = new ProjectSetup();
				IntPtr[] handles = BFS.Window.GetAllWindowHandles() ;
				
				foreach (IntPtr handle in handles)
				{
					string path = ExplorerWindows.GetPath(handle, false);
					if (path != "")
					{
						newsetup.AddProgram(path, handle);
					}
				}
				
				SavedSetups.AddSetup(ProfileName, newsetup);
				SavedSetups.ProjectPath = currPath;
				SaveProgramSettings(SavedSetups, currDirectory);
				BFS.Dialog.ShowMessageInfo("Stored Setup: " + currDirectory);
            }
        }
        catch (Exception e)
        {
            if (ErrorMessages) BFS.Dialog.ShowMessageError("Run:\n" + e.ToString());
        }
	}

    public static void SaveProgramSettings(ProjectSetups Data, string setupName) // store all window settings in an xml file with the provided filename
    {
        XmlSerializer XmlSer = new XmlSerializer(typeof(ProjectSetups));         // Provides the methods for XML-Serialization
        // will be stored in the users local DisplayFusion AppData folder:
		string destination = Environment.ExpandEnvironmentVariables("%userprofile%\\AppData\\Local\\DisplayFusion");
		string p = "";
        bool ready2copy = false; // Copy only if destination folder exists
        
		try
		{
			if (Directory.Exists(destination))  // DisplyFusion user folder found?
			{
				// Creat a subfolder if it doesn't exist, yet
				destination = destination + "\\ProjectSetups";
				ready2copy = Directory.Exists(destination);
				if (!ready2copy)
				{
					ready2copy = Directory.CreateDirectory(destination).Exists;
				}
			}
			p = destination + "\\" + setupName.GetHashCode() + " - " + setupName + ".xml"; // Full Filename with path
		}
		
        catch (Exception e) 
		{
			if (ErrorMessages) BFS.Dialog.ShowMessageError("SaveProgramSettings:\n" + e.ToString());
		}
            
        if (ready2copy) // if destination folder exists
        {
            FileStream DStream = new FileStream(p, FileMode.Create);     // Create the Filestream, overwrite mode

            try
            {
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); // Use this object
                ns.Add("", "");                                             // to prevent that attributes are added in the files

                XmlWriterSettings xws = new XmlWriterSettings();            // Use this object to
                xws.Indent = true;                                          // - add line feeds and indents
                xws.CloseOutput = true;                                     // - close stream after writing
                xws.Encoding = Encoding.Default;                            // - set encoding
                xws.IndentChars = "      ";                                 // - set indent depth
                xws.NewLineHandling = NewLineHandling.None;                 // - handle line feeds properly

                using (XmlWriter writer = XmlWriter.Create(DStream, xws))   // Now serialize
                {
                    XmlSer.Serialize(writer, Data, ns);
                    writer.Close();
                }
            }

			catch (Exception e) 
			{
				if (ErrorMessages) BFS.Dialog.ShowMessageError("SaveProgramSettings_2:\n" + e.ToString());
			}

            finally
            {
                if (!(DStream == null)) DStream.Close();                    // Close the stream
            }       
        }
    }

    public static ProjectSetups LoadProjectSetups(string setupName)   
    {
        ProjectSetups r = new ProjectSetups();
        XmlSerializer XmlSer = new XmlSerializer(typeof(ProjectSetups)); // Provides the methods for XML-Serialization
        
		string destination = Environment.ExpandEnvironmentVariables("%userprofile%\\AppData\\Local\\DisplayFusion");
		string p = "";
        bool ready2copy = false; // Copy only if destination folder exists
        
        if (Directory.Exists(destination))  // DisplyFusion user folder found?
        {
            // Creat a subfolder, if it doesn't exist, yet
            destination = destination + "\\ProjectSetups";
            ready2copy = Directory.Exists(destination);
            if (!ready2copy)
            {
                ready2copy = Directory.CreateDirectory(destination).Exists;
            }
        }
		
		p = destination + "\\" + setupName.GetHashCode() + " - " + setupName + ".xml"; // Full Filename with path

        FileStream DStream = null;
        try
        {
            if (File.Exists(p))
            {
                DStream = new FileStream(p, FileMode.Open);         // Create the Filestream
                r = (ProjectSetups)XmlSer.Deserialize(DStream);     // and load the Data 
            }
        }

        catch (Exception e) 
		{
			if (ErrorMessages) BFS.Dialog.ShowMessageError("LoadProjectSetups:\n" + e.ToString());
		}

        finally
        {
            if (!(DStream == null)) DStream.Close();                // Done
            if (r == null) r = new ProjectSetups();        
        }
        return r;
    }

	public static string buildProfileName(Rectangle[] screens)
	{
		// needs System.Text to have StringBuilder class		
		StringBuilder pname = new StringBuilder();
		
		for (int i = 0; i < screens.Length; i++) // For each monitor
		{
			// Add monitors resolution in the format "[<Width>x<Height>, <Y>]"
			pname.Append("[");
			pname.Append(screens[i].Width);
			pname.Append("x");
			pname.Append(screens[i].Height);
			if(screens[i].X!=0 || screens[i].Y!=0) // Primary screen has coordinates [0,0]
			{
				// Add the y-coordinate, if not primary screen
				pname.Append(",");
				pname.Append(screens[i].Y);
			}
			pname.Append("]");
		}
		
		return pname.ToString();
	}

	[Serializable]
	public class ProjectSetups     // list of ProjectSetups per Monitor Konfiguration
	{
		public ProjectSetups() { } // empty constructor is needed to make the class serializable

		public string ProjectPath = "";
		public XMLDictionary<string, ProjectSetup> Setups = new XMLDictionary<string, ProjectSetup>();  // list of Programs

		public void AddSetup(string monconfig, ProjectSetup setup)  
		{
			if(Setups.ContainsKey(monconfig))
			{
				Setups[monconfig] = setup;
			}
			else
			{
				Setups.Add(monconfig, setup);
			}
		}
		
		public bool HasSetups()
		{
			if (Setups.Count > 0) return true;
			return false;
		}
		
		public ProjectSetup GetSetup(string monconfig)
		{
			if(Setups.ContainsKey(monconfig))
			{
				return Setups[monconfig];
			}
			else
			{
				return Setups.First().Value;
			}
		}
	}

	[Serializable]
	public class ProjectSetup      // list of window settings
	{
		public ProjectSetup() { }  // empty constructor is needed to make the class serializable

		public XMLDictionary<string, Rectangle> Prgrms = new XMLDictionary<string, Rectangle>();  // list of Programs

		public void AddProgram(string name, IntPtr handle)  
		{
			if(Prgrms.ContainsKey(name))
			{
				Prgrms[name] = BFS.Window.GetBounds(handle);
			}
			else
			{
				Prgrms.Add(name, BFS.Window.GetBounds(handle));
			}
		}
	}

}


// ***** XMLDictionary *****
// A Module to provide a dictionary which is serializable.
// Purpose: e.g. ini-files
// Paul Welter 3/5/2006
//
// http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx
public class XMLDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

        bool wasEmpty = reader.IsEmptyElement;
        reader.Read();

        if (wasEmpty)
            return;

        while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
        {
            reader.ReadStartElement("item");

            reader.ReadStartElement("key");
            TKey key = (TKey)keySerializer.Deserialize(reader);
            reader.ReadEndElement();

            reader.ReadStartElement("value");
            TValue value = (TValue)valueSerializer.Deserialize(reader);
            reader.ReadEndElement();

            this.Add(key, value);

            reader.ReadEndElement();
            reader.MoveToContent();
        }
        reader.ReadEndElement();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

        // Addition by Christian Treffler, 6/9/2010:
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); // Use this object
        ns.Add("", "");                                             // to prevent that attributes are added in the files
        // End of addition

        foreach (TKey key in this.Keys)
        {
            writer.WriteStartElement("item");

            writer.WriteStartElement("key");
            keySerializer.Serialize(writer, key, ns);       // Added ns in this call
            writer.WriteEndElement();

            writer.WriteStartElement("value");
            TValue value = this[key];
            valueSerializer.Serialize(writer, value, ns);   // Added ns in this call
            writer.WriteEndElement();

            writer.WriteEndElement();
        }
    }
}


// The following code is adapted from this solution:
// https://stackoverflow.com/questions/36886355/retrieve-the-full-path-of-an-explorer-window-through-a-handle-in-c-sharp
// It builds a directory of all open Explorer windows
public static class ExplorerWindows
{
    static Guid CLSID_ShellApplication = new Guid("13709620-C279-11CE-A49E-444553540000");
    static Type shellApplicationType = Type.GetTypeFromCLSID(CLSID_ShellApplication, true);
    static object shellApplication = null;
    static object windows = null;
    static Type windowsType = null;
    static object count = null;
    static Dictionary<IntPtr, string> ExpWndws = null;  // list of explorer windows
	static int index = 0;
	static IntPtr ThisScriptHandle = IntPtr.Zero;
	public static bool ErrorMessages = false;
    
    public static void InitExplorerHandler(IntPtr thisscripthandle)
    {
        shellApplication = Activator.CreateInstance(shellApplicationType);
        windows = shellApplicationType.InvokeMember("Windows", System.Reflection.BindingFlags.InvokeMethod, null, shellApplication, new object[] { });        
        windowsType = windows.GetType();
        count = windowsType.InvokeMember("Count", System.Reflection.BindingFlags.GetProperty, null, windows, null);
        ExpWndws = new Dictionary<IntPtr, string>();
		ThisScriptHandle = thisscripthandle;
        
        Parallel.For(0, (int)count, (i, state) =>
        {
            try
            {
				object item = windowsType.InvokeMember("Item", System.Reflection.BindingFlags.InvokeMethod, null, windows, new object[] { i });
                Type itemType = item.GetType();
                string itemName = (string)itemType.InvokeMember("Name", System.Reflection.BindingFlags.GetProperty, null, item, null);
                if (itemName == "Windows Explorer" || itemName == "File Explorer" || itemName == "Explorer")
                {
					string itemHandle = itemType.InvokeMember("HWND", System.Reflection.BindingFlags.GetProperty, null, item, null).ToString();
                    // Cannot cast the member "HWND" to IntPtr, therefore need to find a different way get the handle of the window
					foreach (IntPtr handle in BFS.Window.GetAllWindowHandles())
					{
						if (handle.ToString() == itemHandle)
						{
							if(!ExpWndws.ContainsKey(handle))
							{
								string itemPath = (string)itemType.InvokeMember("LocationURL", System.Reflection.BindingFlags.GetProperty, null, item, null);
								itemPath = itemPath.Replace(@"file:///", "");
								ExpWndws.Add(handle, itemPath);
							}
							break;
						}
					}
                }
            }
            catch (Exception e)
            {
                if (ErrorMessages) BFS.Dialog.ShowMessageError("GetPath:\n" + e.ToString());
            }
        });
    }
    
    public static string GetPath(IntPtr windowHandle, bool decode)
    {
        string returnPath = "";
        
        if(ExpWndws.ContainsKey(windowHandle))
        {
            returnPath = ExpWndws[windowHandle];
            if(decode)
            {
				returnPath = HttpUtility.UrlDecode(returnPath, System.Text.Encoding.Default);
            }
        }

        return returnPath;
    }
	
	public static IntPtr GetHandle(string path, bool close_duplicates)
    {
		IntPtr ret = IntPtr.Zero;
		foreach (KeyValuePair<IntPtr, string> window in ExpWndws) 
		{
			if(window.Value == path)
			{
				if (ret != IntPtr.Zero)
				{
					// Close the duplicate window. If it is the window which is the handle for this 
					// scripted function, close the other one.
					IntPtr forClosure = window.Key;
					if(forClosure == ThisScriptHandle)
					{
						forClosure = ret;
						ret = window.Key;
					}
					try
					{
						BFS.Window.Close(forClosure);
					}
					catch {}
				}
				else
				{
					ret = window.Key;
				}
				if(!close_duplicates) break;
			}
		}
        return ret;
    }
}