WinAPI SetWindowPos 不适用于记事本和计算器等简单应用程序

WinAPI SetWindowPos not working for simple apps like notepad and calc

提问人:theateist 提问时间:4/18/2023 更新时间:4/21/2023 访问量:141

问:

我在 Windows 10 上开发。

我想移动外部应用程序并调整其大小。我试着先用记事本和计算器让它工作。但是,无论我做什么,记事本/校准都不会移动或调整大小。我尝试使用 ,但没有任何效果。我调试了代码,并且执行了内部部分。SetWindowPosUpdateWindowMoveWindowforeach

我试图按照此处的建议以管理员身份运行它,但没有帮助。

static void foo()
{    
    foreach (var p in Process.GetProcesses().Where(p => p.ProcessName.ToLower().Contains("calculatorapp")))
    {
        SetWindowPos(p.Handle, HWND.TopMost, 10, 10, 100, 300, (uint)(SWP.SHOWWINDOW));
        int err = Marshal.GetLastWin32Error();

        UpdateWindow(p.Handle);
        //SetWindowPos(p.Handle, 0, 0, 250, 250, true);
        MoveWindow(p.Handle, 0, 0, 250, 250, true);
    }
}
C# WinAPI 设置WindowPOS 移动窗口

评论

4赞 Hans Passant 4/18/2023
您需要一个窗口句柄,而不是一个进程句柄。就像 Process.MainWindowHandle 提供的那样。不适用于 Win10 中的 calc 和 Win11 中的记事本,它们现在是 UWP 应用。 请改用 System.Windows.Automation。

答:

-1赞 Torrecto - MSFT 4/21/2023 #1

正如汉斯·帕桑特(Hans Passant)所说,您需要这样的窗把手。

HWND hwnd=(HWND)0x0xxxxxx;

我在这里使用 spy++ 来获取记事本的窗口句柄。然后用于将记事本移动到新位置并获取新大小。Setwindowposenter image description here

评论

0赞 Torrecto - MSFT 4/28/2023
@theateist你好,对这个答案有什么想法吗?