请教:我在C#里用[DllImport("user32.dll")]调用一个关闭显示器的API,代码在窗体程序里测试很正常,将代码写到服务里面却不能关闭显示器. 主要代码如下:
public partial class Service1 : ServiceBase
{
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
private const uint WM_SYSCOMMAND = 0x0112;
private const int SC_MONITORPOWER = 0xf170;
public static void TurnOn() //开启显示器
{
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, -1);
string path = @"c:\scr.log";
StreamWriter log = new StreamWriter(path,true);
log.WriteLine(DateTime.Now.ToString()+" : Turn On!" );
log.Close();
}
public static void TurnOff() //关闭显示器
{
int i = 100;
i=SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
string path = @"c:\scr.log";
StreamWriter log = new StreamWriter(path,true);
log.WriteLine(DateTime.Now.ToString() + " : Turn Off! Result is "+i.ToString());
log.Close();
}
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1.Start();
}
protected override void OnStop()
{
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (DateTime.Now.Second >= 17)
{
TurnOff();
}
else{
TurnOn();
}
}
}
log文件记录的信息显示TurnOn()和TurnOff()都执行了,且调用的API返回值为1,与用窗体运行此段代码的返回值相同,可是显示器不关闭。请教是什么原因,该如何解决?