Working Experience - MoveWindow API 失败/无效

写在前面

当然过程不可能这么顺风顺水,毕竟对 Win32 API 不熟悉,并且国内搜索引擎和博客质量较低(不误导你就算好了),最后还是通过 Google -> StackOverflow 找到答案。

正文

问题描述:使用 C# 调用 MoveWindow API 改变外部程序窗体位置和尺寸,使用 Spy++ 查看输入的外部程序窗体句柄是正确的,但是该 API 就是不起作用。
解决过程:

  • 查看官方文档,知如果 API 运行正确,返回值为非零. Debug 模式下查看返回值为零.
  • 为了获取更多错误信息,可以使用 GetLastError 函数。具体形式如下:
/**************************************************************************
* 注意:
* 1. 引入 API 的地方头部添加 SetLastError = true
* 2. GetLastWin32Error 在 System.Runtime.InteropServices.Marshal 命名空间下
**************************************************************************/

[DllImport("user32.dll", SetLastError = true)]
internal static extern bool MoveWindow(IntPtr hwnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

// 这里调用 MoveWindow API

int i = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
  • 得到错误码为 5,查看官方文档得知失败原因为被拒绝访问。根据实际情况推算为低权限程序访问高权限程序。使用管理员权限运行程序后再调用该 API,正常运行。

参考

stack overflow - 《WinAPI MoveWindow function not working for some windows》

猜你喜欢

转载自www.cnblogs.com/zdfffg/p/10868044.html