在C#中,EnumDisplayMonitors
函數用于枚舉所有可用的顯示監視器。要處理用戶輸入,您需要首先獲取用戶想要查詢的顯示監視器的索引,然后使用該索引調用EnumDisplayMonitors
函數。以下是一個簡單的示例,說明如何處理用戶輸入并獲取顯示監視器的相關信息:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace EnumDisplayMonitorsExample
{
class Program
{
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr hwnd, EnumMonitorDelegate lpfnEnum, IntPtr lParam);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate bool EnumMonitorDelegate(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
static void Main(string[] args)
{
Console.WriteLine("請輸入要查詢的顯示監視器的索引:");
int monitorIndex = int.Parse(Console.ReadLine());
if (EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, MonitorCallback, IntPtr.Zero))
{
Console.WriteLine($"顯示監視器 {monitorIndex} 的信息:");
Console.WriteLine($"設備名: {monitorInfo.DeviceName}");
Console.WriteLine($"工作區: {monitorInfo.WorkArea}");
Console.WriteLine($"分辨率: {monitorInfo.Bounds}");
}
else
{
Console.WriteLine("無法獲取顯示監視器信息。");
}
}
private static void MonitorCallback(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData)
{
monitorInfo.DeviceName = MonitorFromWindow(hMonitor, MONITOR_DEFAULTTOPRIMARY).DeviceName;
monitorInfo.WorkArea = MonitorFromWindow(hMonitor, MONITOR_DEFAULTTOPRIMARY).WorkArea;
monitorInfo.Bounds = MonitorFromWindow(hMonitor, MONITOR_DEFAULTTOPRIMARY).Bounds;
if (monitorIndex == 0)
{
monitorInfo = new MONITORINFOEX();
monitorInfo.cbSize = (uint)Marshal.SizeOf(monitorInfo);
MonitorFromWindow(hMonitor, MONITOR_DEFAULTTOPRIMARY, out monitorInfo);
}
}
private static IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags)
{
return NativeMethods.MonitorFromWindow(hwnd, dwFlags);
}
}
}
在這個示例中,我們首先獲取用戶輸入的顯示監視器索引,然后調用EnumDisplayMonitors
函數。在回調函數MonitorCallback
中,我們使用MonitorFromWindow
函數獲取顯示監視器的相關信息,并將其存儲在monitorInfo
結構體中。最后,我們將這些信息輸出到控制臺。