2017-02-11 178 views
0

我試圖讓自己在C#中的眼睛保護程序,應該在工作一段時間後使屏幕變暗。爲了改變屏幕亮度,我跟着這個(https://www.codeproject.com/Articles/47355/Setting-Screen-Brightness-in-C)文章使用SetDeviceGammaRamp方法。我的代碼如下:SetDeviceGammaRamp只是閃爍屏幕

private unsafe void dimScreen() 
    { 
     var brightness = 10; 

     short* gArray = stackalloc short[3 * 256]; 
     short* idx = gArray; 

     for (int j = 0; j < 3; j++) 
     { 
      for (int i = 0; i < 256; i++) 
      { 
       int arrayVal = i * (brightness + 128); 

       if (arrayVal > 65535) 
        arrayVal = 65535; 

       *idx = (short)arrayVal; 
       idx++; 
      } 
     } 

     SetDeviceGammaRamp(hdc, gArray); 
     Thread.Sleep(10000); 
    } 

然而,代替永久改變亮度(或至少爲10秒)的屏幕只是閃爍半秒鐘。在多次睡眠的週期中調用SetDeviceGammaRamp不會改變這種情況,我得到的僅僅是幾次這樣的閃爍。如果我更改亮度變量,那麼閃爍的亮度也會發生變化,因此我認爲hdc和gArray變量已正確指定。我試圖尋找其他解決方案,但大多數使用這種方法,似乎沒有人有這個問題。任何想法可能是什麼問題?

UPD:似乎問題一直伴隨着通量。它會注意到gamma的變化並將其重置爲先前的值。

+0

照照Windows事件日誌,一些勝算的視頻驅動程序崩潰和自動恢復產生的閃爍假象。嘗試另一臺機器。請注意,這不是調整屏幕亮度的好方法,例如,安全登錄桌面不受影響。不幸的是,用代碼可靠地控制亮度是一個難以捉摸的目標,VESA監視器接口標準並不是一個很好的目標。 –

回答

0

下面是C#中可以設置屏幕亮度的代碼。你可以試試。

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Runtime.InteropServices; 
namespace brightnesscontrol 
{ 
    public partial class Form1 : Form 
    { 
     [DllImport("gdi32.dll")] 
     private unsafe static extern bool SetDeviceGammaRamp(Int32 hdc, void* ramp); 
     private static bool initialized = false; 
     private static Int32 hdc; 
     private static int a; 
     public Form1() 
     { 
      InitializeComponent(); 
     } 
     private static void InitializeClass() 
     { 
      if (initialized) 
       return; 
      hdc = Graphics.FromHwnd(IntPtr.Zero).GetHdc().ToInt32(); 
      initialized = true; 
     } 
     public static unsafe bool SetBrightness(int brightness) 
     { 
      InitializeClass(); 
      if (brightness > 255) 
       brightness = 255; 
      if (brightness < 0) 
       brightness = 0; 
      short* gArray = stackalloc short[3 * 256]; 
      short* idx = gArray; 
      for (int j = 0; j < 3; j++) 
      { 
       for (int i = 0; i < 256; i++) 
       { 
        int arrayVal = i * (brightness + 128); 
        if (arrayVal > 65535) 
         arrayVal = 65535; 
        *idx = (short)arrayVal; 
        idx++; 
       } 
      } 
      bool retVal = SetDeviceGammaRamp(hdc, gArray); 
      return retVal; 
     } 
     private void trackBar1_Scroll(object sender, EventArgs e) 
     { 
     } 
     private void button1_Click(object sender, EventArgs e) 
     { 
      a = trackBar1.Value; 
      SetBrightness(a); 
     } 
    } 
} 

其實你的代碼沒有錯誤。你如何使用這個dimScreen()函數?也許你以一種不合適的邏輯來做這件事。

我發現這裏拍照教程:http://www.lattepanda.com/topic-f11t3020.html