How do I get the “topmost” status of every window in c#

时光怂恿深爱的人放手 提交于 2019-12-12 03:25:03

问题


Actually I wrote my self a programm that sets the topmost status of a specific window to true or false.

I realised this by importing the user32.dll

[DllImport("user32.dll")]

private static extern bool SetWindowPos(...);

Now I was wondering if its possible to get the state of the window and see if the topmost is set and add this to the items I have in a Listview.

Of course I can do this in runtime, depending on the actions I performed, but my programm will not be opend all the time and I dont want to save data somewere.

What I want is to see in the listview if there was set topmost before and than set it true/false on buttonclick. Depending on its state...

So is there something like GetWindowPos to get the topmost state of a specific window ?


回答1:


According to James Thorpe's comment I solved it like this.

First I added the needed dll and const

//Import DLL
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

//Add the needed const
const int GWL_EXSTYLE      = (-20);
const UInt32 WS_EX_TOPMOST = 0x0008;

At this point i recognized that I allways have to add the DLL again when I want to use several functions of it. For example

[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

I thought I can write it like

[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

NOTE: You can not do it like this :D

After this I went to my function that refreshes my ListView and edited it like

//Getting the processes, running through a foreach
//...
//Inside the foreach
int dwExStyle    = GetWindowLong(p.MainWindowHandle, GWL_EXSTYLE);

string isTopMost = "No";

if ((dwExStyle & WS_EX_TOPMOST) != 0)
{
    isTopMost = "Yes";
}

ListViewItem wlv = new ListViewItem(isTopMost, 1);
wlv.SubItems.Add(p.Id.ToString());
wlv.SubItems.Add(p.ProcessName);
wlv.SubItems.Add(p.MainWindowTitle);
windowListView.Items.Add(wlv);

//Some sortingthings for the listview
//end of foreach processes

In this way I can display if the Window has a topmost status.



来源:https://stackoverflow.com/questions/35315788/how-do-i-get-the-topmost-status-of-every-window-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!