日期:2014-05-16  浏览次数:21155 次

如何在服务程序中重启计算机?
本帖最后由 rodsgo 于 2014-03-18 08:26:17 编辑
写了个检测网络的服务程序,该程序在检测到网络不通的时候重启计算机,但下面的代码测试无效
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Runtime.InteropServices; 

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        protected const int SE_PRIVILEGE_ENABLED = 0x2;
        protected const int TOKEN_QUERY = 0x8;
        protected const int TOKEN_ADJUST_PRIVILEGES = 0x20;
        protected const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
        protected const int EWX_LOGOFF = 0x0;
        protected const int EWX_SHUTDOWN = 0x1;
        protected const int EWX_REBOOT = 0x2;
        protected const int EWX_FORCE = 0x4;
        protected const int EWX_POWEROFF = 0x8;
        protected const int EWX_FORCEIFHUNG = 0x10;

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        protected struct LuidStruct
        {
            public int Count;
            public long Luid;
            public int Attr;
        }
        [DllImport("kernel32.dll", ExactSpelling = true)]
        protected static extern IntPtr GetCurrentProcess();

        [DllImport("advapi32.dll", SetLastError = true)]
        protected static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);

        [DllImport("advapi32.dll", SetLastError = true)]
        protected static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);

        [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)]
        protected static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref LuidStruct newst, int len, IntPtr prev, IntPtr relen);

        [DllImport("user32.dll", SetLastError&