blez's : blog

code / design / music and more

Leave a comment

Get exe path from process

        private string GetProcessPath(Process process) {
            using (var searcher = new ManagementObjectSearcher("SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId = " + process.Id.ToString())) {
                using (var results = searcher.Get()) {
                    var mo = results.Cast<ManagementObject>().FirstOrDefault();
                    if (mo != null) return (string) mo["ExecutablePath"];

            return null;

Leave a comment

How to use HTML5 audio in the WebBrowser control?

No matter how new version of Windows you use, the WebBrowser control always uses older version of IE. That’s pretty awful solution since we all know how good IE is. Using meta tags it is possible to say to IE to use a specific version. The following example illustrates how to make a simple html5 audio player playing mp3 directly from some url.

// the obvious..
// webBrowser1 is a WebBrowser control
// someUrl is an url to a mp3 file

var source = "<html><head><meta http-equiv='X-UA-Compatible' content='IE=9'></head><body><audio id='player' style='position: absolute; left: 0; top: 0; width: 100%' controls autoplay='autoplay'><source src='{0}' type='audio/mpeg'>You need a newer version of IE to play this track.</audio></body></html>";
webBrowser1.DocumentText = string.Format(source, someUrl);

Leave a comment

Get the currently focused control

It’s easy to get the currently foreground window (using the GetForegroundWindow API), but what about the currently focused child window?
Here’s one way.

        private static extern IntPtr GetForegroundWindow();

        static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

        static extern uint GetCurrentThreadId();

        static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

        static extern IntPtr GetFocus();

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        public static IntPtr GetCurrentFocusWindow() {
            var remoteThreadId = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
            var currentThreadId = GetCurrentThreadId();
            // AttachThreadInput is needed so we can get the handle of a focused window in another app
            AttachThreadInput(remoteThreadId, currentThreadId, true);
            // Get the handle of a focused window
            IntPtr focussed = GetFocus();

            // Now detach since we got the focused handle
            AttachThreadInput(remoteThreadId, currentThreadId, false);

            return focussed;