更改屏幕的滤色器以与多台显示器一起使用

Posted

技术标签:

【中文标题】更改屏幕的滤色器以与多台显示器一起使用【英文标题】:Change colour filter of screen to work with multiple monitors 【发布时间】:2015-06-29 07:06:34 【问题描述】:

我已经编写了一个程序来更改屏幕的滤色器,类似于 Flux 所做的方式(显示的代码在主要问题 from here 中)。但是,我的几个用户说它不会影响具有两个或更多显示器的其他屏幕。我将如何修改代码以使其正常运行?

【问题讨论】:

它在有两个显示器的机器上什么都不做,还是抛出错误?它只改变一个屏幕吗?用户体验如何? 它显然对第二个屏幕没有任何作用。 【参考方案1】:

你可以这样做

    获取所有连接的监视器 将 get/set 函数应用到 Graphics(或其 HDC)。 注册MonitorInfoInvalidated 事件以重新申请,如果监视器信息失效。

如果您已经依赖于Windows.Forms dll,或者不介意承担这种依赖关系,您可以使用它的Screen 类,正如@HansPassant 在他的answer 中指出的那样。在这种情况下,您将为 SystemEvents.DisplaySettingsChanged 注册一个事件处理程序以触发重新应用您的 get/set 函数,并且您将使用对 CreateDC 和 DeleteDC 的互操作调用从 Screen.DeviceName 获取/释放设备上下文句柄 (IntPtr)财产。下面的代码显示了一个围绕这个类的包装器,它有助于做到这一点:

/// <summary>
/// This is an alternative that uses the Windows.Forms Screen class.
/// </summary>
public static class FormsScreens

    public static void ForAllScreens(Action<Screen, IntPtr> actionWithHdc)
    
        foreach (var screen in Screen.AllScreens)
            screen.WithHdc(actionWithHdc);

    

    public static void WithHdc(this Screen screen, Action<Screen, IntPtr> action)
    
        var hdc = IntPtr.Zero;
        try
        
            hdc = CreateDC(null, screen.DeviceName, null, IntPtr.Zero);
            action(screen, hdc);
        
        finally
        
            if (!IntPtr.Zero.Equals(hdc))
                DeleteDC(hdc);
        
    

    private const string GDI32 = @"gdi32.dll";

    [DllImport(GDI32, EntryPoint = "CreateDC", CharSet = CharSet.Auto)]
    static extern IntPtr CreateDC(string lpszDriver, string lpszDevice, string lpszOutput, IntPtr lpInitData);

    [DllImport(GDI32, CharSet = CharSet.Auto)]
    private static extern bool DeleteDC([In] IntPtr hdc);

如果您不想对Windows.Forms dll 产生新的依赖,下面的ConnectedMonitors 类提供了相同的功能:

/// <summary>
/// This is the version that is not dependent on Windows.Forms dll.
/// </summary>
public static class ConnectedMonitors

    private static readonly bool _isSingleMonitor = GetSystemMetrics(SM_CMONITORS) == 0;
    private static Lazy<List<MonitorInfo>> _monitors = new Lazy<List<MonitorInfo>>(GetMonitors, true);

    public static event Action MonitorInfoInvalidated;

    public class MonitorInfo
    
        public readonly IntPtr MonitorHandle;
        public readonly IntPtr DeviceContextHandle;
        public readonly string DeviceName;
        public readonly bool IsPrimary;
        public readonly Rectangle Bounds;
        public readonly Rectangle WorkArea;

        public void WithMonitorHdc(Action<MonitorInfo, IntPtr> action)
        
            var hdc = DeviceContextHandle;
            var shouldDeleteDC = IntPtr.Zero.Equals(hdc);
            try
            
                if (shouldDeleteDC)
                    hdc = CreateDC(null, DeviceName, null, IntPtr.Zero);
                action(this, hdc);
            
            finally
            
                if (shouldDeleteDC && !IntPtr.Zero.Equals(hdc))
                    DeleteDC(hdc);
            
        

        internal MonitorInfo(
            IntPtr hMonitor, 
            IntPtr hDeviceContext, 
            string deviceName,
            bool isPrimary,
            Rectangle bounds,
            Rectangle workArea)
        
            this.MonitorHandle = hMonitor;
            this.DeviceContextHandle = hDeviceContext;
            this.DeviceName = deviceName;
            this.IsPrimary = isPrimary;
            this.Bounds = bounds;
            this.WorkArea = workArea;
        
    

    public static void CaptureScreen(MonitorInfo mi, string fileName)
    
        CaptureScreen(mi).Save(fileName);
    

    public static Bitmap CaptureScreen(MonitorInfo mi)
    
        Bitmap screenBmp = default(Bitmap);
        mi.WithMonitorHdc((m, hdc) =>
        
            screenBmp = new Bitmap(m.Bounds.Width, m.Bounds.Height, PixelFormat.Format32bppArgb);
            using (var destGraphics = Graphics.FromImage(screenBmp))
            
                var monitorDC = new HandleRef(null, hdc);
                var destDC = new HandleRef(null, destGraphics.GetHdc());
                var result = BitBlt(destDC, 0, 0, m.Bounds.Width, m.Bounds.Height, monitorDC, 0, 0, unchecked((int)BITBLT_SRCCOPY));
                if (result == 0)
                    throw new Win32Exception();
            
        );
        return screenBmp;
    

    public static IEnumerable<MonitorInfo> Monitors
    
        get  return _monitors.Value; 
    

    private static List<MonitorInfo> GetMonitors()
    
        // Get info on all monitors
        var cb = new EnumMonitorsCallback();
        EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, cb.Callback, IntPtr.Zero);

        // Register for events invalidating monitor info.
        SystemEvents.DisplaySettingsChanging += OnDisplaySettingsChanging;
        SystemEvents.UserPreferenceChanged += OnUserPreferenceChanged;

        // Return result.
        return cb.Monitors;
    

    private class EnumMonitorsCallback
    
        public List<MonitorInfo> Monitors = new List<MonitorInfo>();

        public bool Callback(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr lparam)
        
            // Get its info
            var info = new MONITORINFOEX();
            info.Size = Marshal.SizeOf(typeof(MONITORINFOEX));
            GetMonitorInfo(hMonitor, ref info);

            // Decode the info
            var isPrimary = (hMonitor == (IntPtr)PRIMARY_MONITOR) || ((info.Flags & MONITORINFOF_PRIMARY) != 0);
            var bounds = Rectangle.FromLTRB(info.Monitor.Left, info.Monitor.Top, info.Monitor.Right, info.Monitor.Bottom);
            var workArea = Rectangle.FromLTRB(info.WorkArea.Left, info.WorkArea.Top, info.WorkArea.Right, info.WorkArea.Bottom);
            var deviceName = info.DeviceName.TrimEnd('\0');

            // Create info for this monitor and add it.
            Monitors.Add(new MonitorInfo(hMonitor, hdcMonitor, deviceName, isPrimary, bounds, workArea));
            return true;
        
    

    private static void OnDisplaySettingsChanging(object sender, EventArgs e)
    
        InvalidateInfo();
    

    private static void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
    
        InvalidateInfo();
    

    private static void InvalidateInfo()
    
        SystemEvents.DisplaySettingsChanging -= OnDisplaySettingsChanging;
        SystemEvents.UserPreferenceChanged -= OnUserPreferenceChanged;
        var cur = _monitors;
        _monitors = new Lazy<List<MonitorInfo>>(GetMonitors, true);
        var notifyInvalidated = MonitorInfoInvalidated;
        if (notifyInvalidated != null)
            notifyInvalidated();
    

    #region Interop

    private const string USER32 = @"user32.dll";
    private const string GDI32 = @"gdi32.dll";
    private const int PRIMARY_MONITOR = unchecked((int)0xBAADF00D);
    private const int MONITORINFOF_PRIMARY = 0x00000001;
    private const int SM_CMONITORS = 80;
    private const int BITBLT_SRCCOPY = 0x00CC0020;
    private const int BITBLT_CAPTUREBLT = 0x40000000;
    private const int BITBLT_CAPTURE = BITBLT_SRCCOPY | BITBLT_CAPTUREBLT;

    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    private struct MONITORINFOEX
    
        public int Size;
        public RECT Monitor;
        public RECT WorkArea;
        public uint Flags;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
        public string DeviceName;
    

    delegate bool EnumMonitorsDelegate(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData);

    [DllImport(USER32, CharSet=CharSet.Auto)]
    private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, EnumMonitorsDelegate lpfnEnum, IntPtr dwData);

    [DllImport(USER32, CharSet = CharSet.Auto)]
    private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFOEX lpmi);

    [DllImport(USER32, CharSet = CharSet.Auto)]
    private static extern int GetSystemMetrics(int nIndex);

    [DllImport(GDI32, EntryPoint = "CreateDC", CharSet = CharSet.Auto)]
    static extern IntPtr CreateDC(string lpszDriver, string lpszDevice, string lpszOutput, IntPtr lpInitData);

    [DllImport(GDI32, CharSet = CharSet.Auto)]
    private static extern bool DeleteDC([In] IntPtr hdc);

    [DllImport(GDI32, CharSet = CharSet.Auto)]
    public static extern int BitBlt(HandleRef hDC, int x, int y, int nWidth, int nHeight,
                                    HandleRef hSrcDC, int xSrc, int ySrc, int dwRop);
    #endregion

您的用例的使用示例,使用稍微修改的SetLCDbrightness 方法:

private bool SetLCDbrightness(IntPtr hdc, Color c)

    short red = c.R;
    short green = c.G;
    short blue = c.B;

    unsafe
    
        short* gArray = stackalloc short[3 * 256];
        short* idx = gArray;
        short brightness = 0;
        for (int j = 0; j < 3; j++)
        
            if (j == 0) brightness = red;
            if (j == 1) brightness = green;
            if (j == 2) brightness = blue;
            for (int i = 0; i < 256; i++)
            
                int arrayVal = i * (brightness);
                if (arrayVal > 65535) arrayVal = 65535;
                *idx = (short)arrayVal;
                idx++;
            
        
        // For some reason, this always returns false?
        bool retVal = SetDeviceGammaRamp(hdc, gArray);
    
    return false;

调用如下:

// ConnectedMonitors variant
public void SetBrightness(Color c)

    foreach (var monitor in ConnectedMonitors.Monitors)
        monitor.WithMonitorHdc((m, hdc) => SetLCDbrightness(hdc, c));


// Variant using the Windows.Forms Screen class
public void SetBrightness(Color c)

    var setBrightness = new Action<Screen, IntPtr>((s, hdc) => SetLCDbrightness(hdc, c));
    FormsScreens.ForAllScreens(setBrightness);

请注意,它还允许进行一些其他有趣的事情,例如截屏:

var n = 0;
foreach (var m in ConnectedMonitors.Monitors)
    ConnectedMonitors.CaptureScreen(m, string.Format(@"c:\temp\screen0.bmp", n++));

【讨论】:

哇,没想到会这么复杂——很棒的工作。当我尝试编译时出现一个问题 - 我得到:“找不到类型或命名空间名称‘Lazy’”。不幸的是,我无法“解决”这个问题。 @DanW 类System.Lazy&lt;T&gt; 可以在System 命名空间中找到。确保您有 using System; 声明。它从 .NET 4 开始可用。如果您使用的是旧版本的 .NET,创建一个简单的替换实现应该不难。 是的,由于潜在的更大用户群,我倾向于将 .NET 3.5 用于我的所有程序。创建它需要超过 5-10 行代码供您添加吗?如果是这样,我会看看我是否可以为这个程序切换到 .NET 4。 @DanW 你可以找到一个here。它有超过 10 行代码,所以我想是时候升级到更新的 .NET 版本了;-) 哈哈,很公平 - 我会捏它。顺便问一下,你的答案与汉斯的优劣相比如何?【参考方案2】:

当机器有多个显示适配器时,您的代码无法工作,这种情况并不少见。所以 GetDC() 不正确,您需要改为 pinvoke CreateDC(),将屏幕名称(如 @"\\.\DISPLAY1")作为第一个参数传递,其余为空。使用 DeleteDC() 进行清理。

使用Screen.DeviceName 属性获取设备名称,Screen.AllScreens() 枚举监视器。你可能应该订阅 SystemEvents.DisplaySettingsChanged 事件来检测用户启用了监​​视器,我没有硬件来检查这个。

【讨论】:

谢谢。就利弊而言,您的答案与 Alex 的答案相比如何?老实说,我可能不是第一个应该判断赏金获胜者的人。尽管就我个人而言,我需要您的答案更加充实,最好是使用代码。顺便说一句,我相信你知道,但以防万一它有什么不同,请注意 GetDC() 不用于写入屏幕颜色的方法,只读取它。也许你的意思是 GetHdc()? 我不明白他为什么把它弄得这么复杂,使用 Screen 类很容易。 @HansPassant,你说得对,这可以使用 Windows 窗体 Screens 类来完成,它与我的回答中的 ConnectedMonitors 类几乎相同。这是我在一个软件中使用的东西,它不需要任何其他对 Windows 窗体的依赖,并且具有额外的功能来确定显示设备是否可拆卸、活动、它们的物理尺寸是什么、支持的分辨率......如果 OP 不需要阻止对 Windows 窗体的依赖,则使用其 Screens 类的解决方案同样可以正常工作。我会相应地更新我的答案。

以上是关于更改屏幕的滤色器以与多台显示器一起使用的主要内容,如果未能解决你的问题,请参考以下文章

ffmpeg:如何使用 ffmpeg 在视频中仅放置颜色叠加视频或应用不同类型的滤色器(如 instagram)

css 背景CSS图像适合屏幕并具有滤色器

将滤色器添加到图像的暗部分,将另一个滤色器添加到图像的亮部分?

如何使用 GPUImageLibrary“减去”滤色器?

在 ubuntu 中安装 Ipopt 求解器以与 Pyomo 一起使用

如何将滤色器应用于具有所有子项的视图