- 1 year ago
C# Windows Forms How to Blank Out all other monitors
Comment
1 / 1
To blank out all other monitors in a multi-monitor setup using C# and Windows Forms, you can use P/Invoke (Platform Invocation Services) to call native Windows API functions. Specifically, you'll need to use the EnumDisplayMonitors
and SendMessage
functions to manipulate the screens. Here's a step-by-step guide:
- Add the necessary using directives at the top of your C# file:
csharpusing System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
- Define the necessary native Windows API functions using P/Invoke:
csharpprivate const int MONITOR_DEFAULTTOPRIMARY = 1;
private const int MONITOR_DEFAULTTONEAREST = 2;
private const int WM_SYSCOMMAND = 0x0112;
private const int SC_MONITORPOWER = 0xF170;
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, EnumMonitorsDelegate lpfnEnum, IntPtr dwData);
[DllImport("user32.dll")]
private static extern IntPtr MonitorFromWindow(IntPtr hwnd, int dwFlags);
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);
private delegate bool EnumMonitorsDelegate(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;
}
- Define a method to blank out all other monitors:
csharpprivate void BlankOutOtherMonitors()
{
EnumMonitorsDelegate enumMonitorsDelegate = (IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData) =>
{
IntPtr hWnd = MonitorFromWindow(hMonitor, MONITOR_DEFAULTTONEAREST);
if (hWnd != IntPtr.Zero && hWnd != Handle)
{
SendMessage(hWnd, WM_SYSCOMMAND, SC_MONITORPOWER, 2); // Turn off monitor
}
return true;
};
EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, enumMonitorsDelegate, IntPtr.Zero);
}
- Call the
BlankOutOtherMonitors()
method whenever you want to blank out all other monitors. For example, you can call it in a button click event or any other suitable event handler.
Please note that this code will blank out all other monitors by turning off their power. To turn them back on, you can use SendMessage(hWnd, WM_SYSCOMMAND, SC_MONITORPOWER, -1)
.
Keep in mind that this code may require elevated privileges, depending on the system's power settings and security policies.