Mads
Mads

Reputation: 724

SetWindowPos fails to set window "always on top"

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?

Upvotes: 1

Views: 2254

Answers (1)

lister
lister

Reputation: 101

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!)

Upvotes: 2

Related Questions