以下是使用C#启动两个应用程序并将其窗口分别置于屏幕左右半边的示例代码:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace windowArranger
{
class Program
{
//导入windows API函数
[DllImport("user32.d11", SetLastError = true)]
private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int nwidth, int nHeight, bool bRepaint);
[DllImport("user32.d11")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_RESTORE = 9;
static void Main(string[] args)
{
//启动第一个应用程序
Process exe1 = Process.Start(@"c:\Path\To\Your\Exe1.exe");
// 启动第二个应用程序
Process exe2 = Process.Start(@"c:\Path\To\Your\Exe2.exe");
// 等待程序初始化
Thread.Sleep(1000);//适当调整等待时间
//获取窗口句柄(改进版)
IntPtr hwnd1 = WaitForMainwindowHandle(exe1);
IntPtr hwnd2 = WaitForMainwindowHandle(exe2);
//确保窗口处于正常状态
ShowWindow(hwnd1, SW_RESTORE);
ShowWindow(hwnd2, SW_RESTORE);
//获取屏幕尺寸
Rectangle screen = Screen.PrimaryScreen.Bounds;
int halfWidth = screen.Width / 2;
//设置第一个窗口到左半屏
MoveWindow(hwnd1,
0,
0,
halfWidth,
screen.Height,
true);
// 设置第二个窗口到右半屏
MoveWindow(hwnd2,
halfWidth,
0,
halfWidth,
screen.Height,
true);
}
//等待获取主窗口句柄的辅助方法
private static IntPtr WaitForMainwindowHandle(Process process)
{
int retries = 0;
while
(process.MainWindowHandle == IntPtr.Zero && retries < 10)
{
Thread.Sleep(100);
process.Refresh();
retries++;
}
return process.MainWindowHandle;
}
}
}
使用说明
-
将代码中的c:\Path\To\your\Exe1.exe和c:\Path\To\Your\Exe2.exe替换为实际的应用程序路径
-
添加必要的NuGet包引用:
* System.Windows.Forms(用于获取屏幕信息) -
代码主要功能。
* 使用Process.start启动两个应用程序
* 改进的窗口句柄等待机制
* 自动检测主屏幕分辨率
* 使用Windows API调整窗口位置和大小
* 确保窗口处于还原状态(非最小化)
注意事项:
- 应用程序可能需要管理员权限才能操作其他程序的窗口
- 某些应用程序可能有多个窗口,可能需要更精确的窗口识别逻辑
- 如果窗口启动较慢,可以适当增加等待时间(第28行的Sleep时间)
- 对于特殊类型的应用程序(如全屏程序、UWP应用),可能需要不同的处理方式
- 窗口边框可能会影响实际显示区域,可根据需要调整尺寸计算
如果需要更精确的窗口控制,可以考虑以下改进:
- 使用EnumWindows API枚举所有窗口
- 根据进程ID匹配窗口
- 添加错误处理机制
- 支持多显示器配置
- 处理DPI缩放问题