使用advapi32.dll在64位系统上安装Windows服务

时间:2016-03-28 20:48:07

标签: c# windows-services administrator advapi32

我想将服务安装到Service Manager并运行它。我的代码如下:

 using System;
 using System.Runtime.InteropServices;
 class Ana
 {
    static void Main()
    {
        IntPtr sc_handle=OpenSCManager(null,null,2);
        IntPtr sv_handle = CreateService(sc_handle, "deneme", "deneme", 16, 16, 2, 0, @"D:\ServisDeneme2.exe", null, null, null, null, null);
        int i=StartService(sv_handle,0,null);
        CloseServiceHandle(sc_handle);
    }

    [DllImport("advapi32.dll")]
    public static extern IntPtr OpenSCManager(string machine, string db, int parameter);

    [DllImport("advapi32.dll")]
    public static extern IntPtr CreateService(IntPtr SC_HANDLE, string lpSvcName, string lpDisplayName, int dwDesiredAccess, int dwServiceType, int dwStartType, int dwErrorControl, string lpPathName, string lpLoadOrderGroup, object lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);

    [DllImport("advapi32.dll")]
    public static extern void CloseServiceHandle(IntPtr SCHANDLE);

    [DllImport("advapi32.dll")]
    public static extern int StartService(IntPtr SVHANDLE, int dwNumServiceArgs, string[] lpServiceArgVectors); 
}

using System; using System.Runtime.InteropServices; class Ana { static void Main() { IntPtr sc_handle=OpenSCManager(null,null,2); IntPtr sv_handle = CreateService(sc_handle, "deneme", "deneme", 16, 16, 2, 0, @"D:\ServisDeneme2.exe", null, null, null, null, null); int i=StartService(sv_handle,0,null); CloseServiceHandle(sc_handle); } [DllImport("advapi32.dll")] public static extern IntPtr OpenSCManager(string machine, string db, int parameter); [DllImport("advapi32.dll")] public static extern IntPtr CreateService(IntPtr SC_HANDLE, string lpSvcName, string lpDisplayName, int dwDesiredAccess, int dwServiceType, int dwStartType, int dwErrorControl, string lpPathName, string lpLoadOrderGroup, object lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword); [DllImport("advapi32.dll")] public static extern void CloseServiceHandle(IntPtr SCHANDLE); [DllImport("advapi32.dll")] public static extern int StartService(IntPtr SVHANDLE, int dwNumServiceArgs, string[] lpServiceArgVectors); } 此代码在我的32位计算机上运行良好,但在64位计算机上不起作用。我如何为64位做同样的工作?

2 个答案:

答案 0 :(得分:0)

我认为您必须在x86中编译应用程序才能在64位计算机上正常运行。

或者你可以做这样的事情:

Using a 32bit or 64bit dll in C# DllImport

答案 1 :(得分:0)

我做到了!问题是没有管理员权限。它与32位/ 64位区别无关。要创建,启动,停止服务,服务控制程序必须具有管理员权限。我已经启动了具有管理员权限的命令行,并且该程序正常运行。