gpt4 book ai didi

c# - 如何正确获取鼠标下的窗口?

转载 作者:行者123 更新时间:2023-11-30 12:31:09 29 4
gpt4 key购买 nike

正如我所读到的,在鼠标下获取窗口的方法是使用 WindowFromPoint,这就是我所做的,但是,如果我将鼠标放在其他窗口,它将始终返回我的窗口句柄!

这是我的代码:

NativeMethods.POINT p;

if (NativeMethods.GetCursorPos(out p))
{

IntPtr hWnd = NativeMethods.WindowFromPoint(p);
NativeMethods.GetWindowModuleFileName(hWnd, fileName, 2000);

string WindowTitle= fileName.ToString().Split('\\')[fileName.ToString().Split('\\').Length - 1];
// WindowTitle will never change, it will get my window only!

}

////////////////////////////////////////////////////////////////////////////////////////

static class NativeMethods
{

[DllImport("user32.dll")]
public static extern IntPtr WindowFromPoint(POINT Point);

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint GetWindowModuleFileName(IntPtr hwnd,
StringBuilder lpszFileName, uint cchFileNameMax);

[DllImport("user32.dll")]
public static extern bool GetCursorPos(out NativeMethods.POINT lpPoint);


[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;

public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}

public static implicit operator System.Drawing.Point(POINT p)
{
return new System.Drawing.Point(p.X, p.Y);
}

public static implicit operator POINT(System.Drawing.Point p)
{
return new POINT(p.X, p.Y);
}
}

[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
}

编辑

因为我在 WPF 中工作,下面是我在 WPF 中使用 invoke 的尝试:

void dispatcherOp_Completed(object sender, EventArgs e)
{

System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
delegate()
{
System.Windows.Threading.DispatcherOperation
dispatcherOp = this.Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
NativeMethods.POINT p;
if (NativeMethods.GetCursorPos(out p))
{
IntPtr hWnd = NativeMethods.WindowFromPoint(p);
NativeMethods.GetWindowModuleFileName(hWnd, fileName, 2000);

uint processID = 0;
uint threadID = GetWindowThreadProcessId(hWnd, out processID);
string filename= Process.GetProcessById((int)processID).MainModule.FileName;
}

}
));
dispatcherOp.Completed -= new EventHandler(dispatcherOp_Completed);
dispatcherOp.Completed += new EventHandler(dispatcherOp_Completed);
}
));


thread.Start();
}

最佳答案

GetWindowModuleFileNamerestricted给调用进程,如果你传递一个属于另一个的 HWND 它将不起作用。

相反,您可以使用 HWND 和 p/invoke GetWindowThreadProcessId() 获取进程 ID,然后您可以 Process.GetProcessById(processId).Ma​​inModule。文件名;.

关于c# - 如何正确获取鼠标下的窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14381032/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com