【问题标题】:Cant destroy arbitrary window using p/invoke in C#无法在 C# 中使用 p/invoke 销毁任意窗口
【发布时间】:2021-12-06 09:28:26
【问题描述】:

我正在使用各种 P/Invoke 函数获取所有窗口,并使用此处 (IsAltTabWindow) 转换为 C# 的代码对其进行过滤:

Why does EnumWindows return more windows than I expected?

public static List<IntPtr> GetWindows()
{
    List<IntPtr> result = new List<IntPtr>();
    GCHandle listHandle = GCHandle.Alloc(result);
    try
    {
        EnumWindowProc callback = new EnumWindowProc(EnumWindow);
        EnumWindows(callback, GCHandle.ToIntPtr(listHandle));
    }
    finally
    {
        if (listHandle.IsAllocated)
            listHandle.Free();
    }
    return result;
}

public static List<IntPtr> GetTaskBarWindows()
{
    List<IntPtr> result = GetWindows().Where(i => IsTaskBarWindow(i)).ToList();
    return result;
}

现在我需要通过它的IntPtr 杀死一个窗口,但是当我调用 var b = DestroyWindow(item.window); 时,我得到了false 作为返回并且窗口不受影响。

使用DestroyWindow 是否有已知限制?我该怎么做才能杀死一个窗口?

注意:有些窗口共享相同的进程(例如 Edge 浏览器),因此我无法通过进程 ID 杀死它 - 它会杀死所有窗口,而我一次只需要一个。 p>

【问题讨论】:

  • "...一个线程不能使用DestroyWindow 来销毁由另一个线程创建的窗口..." 这也意味着跨进程不会像调用DestroyWindow 的代码将始终位于与创建窗口的线程不同的线程中 - 源代码 - docs.microsoft.com/en-us/windows/win32/api/winuser/…

标签: c# c++ .net-core pinvoke


【解决方案1】:

在@RichardCritten 评论后寻找不同的解决方案并使用PostMessage 而不是 DestroyWindow 并且它有效!

var b = PInvoker.PostMessage(item.window, (uint)PInvoker.WM.CLOSE, 0, 0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多