weixin_43369128
2019-05-31 11:12
采纳率: 100%
浏览 305

C#写的服务程序,调用Win32API不能关闭显示器

请教:我在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,与用窗体运行此段代码的返回值相同,可是显示器不关闭。请教是什么原因,该如何解决?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • blownewbee 2019-05-31 14:30
    已采纳

    因为在服务里面有独立的会话,关闭显示器关闭的是那个用户会话的显示器,而不是登录用户的那个,所以关了没有反应。你得把关屏的程序独立起来在当前桌面进程里调用,服务不直接调用

    点赞 打赏 评论

相关推荐 更多相似问题