Tuesday, July 2, 2013

Extracting XPAH from xmlNode instace

Here is a very simple and elegant function to extract the xpath string of a xml node instance:

static string GetXpath(XmlNode node)
    {
        if (node.Name == "#document")
            return String.Empty;
        return GetXpath(node.SelectSingleNode("..")) + "/" +  (node.NodeType == XmlNodeType.Attribute ? "@":String.Empty) + node.Name;
    }

credit: http://stackoverflow.com/questions/241238/how-to-get-xpath-from-an-xmlnode-instance-c-sharp

Tuesday, February 5, 2013

c# bring another application to foreground

If you ever need to bring another windows process to the foreground or in other words from your code, set focus on another application (not your current running app) and bring it to the front of the screen here is what you need to do:

1) Import the following DLLS:


        [DllImport("user32.dll")]
        public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
        [DllImport("user32.dll")]
         public static extern bool SetForegroundWindow(IntPtr WindowHandle);
        public const int SW_RESTORE = 9;


* Don't forget to add the using statement:
       using System.Runtime.InteropServices;

2) Identify the process you want to bring to the front and set the focus on it's window handle:

private void FocusProcess(string procName)
    {
        Process[] objProcesses = System.Diagnostics.Process.GetProcessesByName(procName);        if (objProcesses.Length > 0)
        {
            IntPtr hWnd = IntPtr.Zero;
            hWnd = objProcesses[0].MainWindowHandle;
            ShowWindowAsync(new HandleRef(null,hWnd), SW_RESTORE);
             SetForegroundWindow(objProcesses[0].MainWindowHandle);
        }
    }