C#ではSetWindowPosを使用してウィンドウを移動します。
SetWindowPos 関数を使用して C# 内でウィンドウを移動できます。以下にサンプルコードを示します。
using System;
using System.Runtime.InteropServices;
namespace WindowMovement
{
class Program
{
// 导入SetWindowPos函数
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
// 定义窗口句柄常量
const int HWND_TOP = 0;
const uint SWP_NOSIZE = 0x0001;
const uint SWP_NOMOVE = 0x0002;
static void Main(string[] args)
{
// 获取当前程序的窗口句柄
IntPtr hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
// 移动窗口到新的位置(例如:将窗口移动到坐标(100,100)的位置)
SetWindowPos(hWnd, (IntPtr)HWND_TOP, 100, 100, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}
}
}
先述のコードでは、SetWindowPos関数はウインドウの位置を移動するために利用されています。これは複数の引数を受け取ります。これらには、ウインドウのハンドル、挿入されるウインドウのハンドル、ウインドウの新しい位置のXとY座標、ウインドウのサイズのcxとcy、およびいくつかのフラグビットパラメータがあります。このサンプルでは、HWND_TOPパラメータを使用してウインドウを最前面に置き、SWP_NOSIZEおよびSWP_NOMOVEパラメータを使用してウインドウのサイズと位置を維持し、ウインドウを移動するだけです。