1

I'm trying to make a small program so I can keep my vlc player always on top in order for me to watch movies on some of my screen while doing other stuff.

I found this code here on SO by another guy. My code looks like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Diagnostics;
using System.Windows.Shapes;
using System.Runtime.InteropServices;

namespace WpfApplication1
{
    public class ProcessManager
    {
        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, uint windowStyle);

        [DllImport("user32.dll")]
        private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);

        public ProcessManager()
        {
            string processName = "vlc";
            //SearchProcessAndModifyState(processName);
        }

        public void SearchProcessAndModifyState(string targetProcessName)
        {
            Process specifiedProcess = null;
            Process[] processes = Process.GetProcesses();
            for (int i = 0; i < processes.Length; i++)
            {
                Process process = processes[i];
                if (process.ProcessName == targetProcessName)
                {
                    specifiedProcess = process;
                    break;
                }
            }
            if (specifiedProcess != null)
            {
                ProcessManager.ShowWindow(specifiedProcess.MainWindowHandle, 1u);
                ProcessManager.SetWindowPos(specifiedProcess.MainWindowHandle, new IntPtr(-1), 0, 0, 0, 0, 3u);
            }
        }
    }
}

Now when I run this program, the vlc window will show up, but it will not stay on top. So I guess the ShowWindow works, but the SetWindowPos doesn't. I created the project by File -> New -> Project... -> Visual C# -> Windows -> WPF Application in Visual Studio 2013 and I'm using Windows 8.1. Anybody know of anything?

Community
  • 1
  • 1
Mads
  • 724
  • 3
  • 10

1 Answers1

2

I had the exact same issue. I solved it by inserting the following just prior to calling SetWindowPos:

const int GWL_EXSTYLE = -20;
const int WS_EX_TOPMOST = 8;

var extStyle = GetWindowLongPtr(hWnd, GWL_EXSTYLE).ToInt64();
extStyle |= WS_EX_TOPMOST;
SetWindowLongPtr(hWnd, GWL_EXSTYLE, new IntPtr(extStyle));

(Both GetWindowLongPtr and SetWindowLongPtr can be looked up on pinvoke.net - posting from memory on my phone or would give a slightly fuller answer!)

lister
  • 101
  • 1
  • 3
  • How do you get this working.. I have https://i.imgur.com/AqZwj6V.png and I can see how to an actual parameter (argument) for `IntPtr hWnd` But I can't see how to get an actual parameter (argument), for `HandRef hWnd` which is what SetWindowLongPtr uses. – barlop Nov 15 '17 at 23:08
  • I see can do that with `HandleRef hr = new HandleRef(null, iptr);` – barlop Nov 15 '17 at 23:12