C# 服务程序 弹窗
1.创建C#服务程序
首先,创建C#服务程序,打开VS2017,添加新项目,选择windows服务,并根据需要命名,如:MyService,确定
如图,切换到代码块
2.初始代码
只有开始和结束函数
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.Threading.Tasks;
namespace MyService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
}
3.添加安装程序
右键步骤2图片空白处,添加安装程序
4.设置属性
首先鼠标左键点击serviceProcessInstaller1,查看右下角的属性,并进行编辑,此处需要将Account更改为LocalSystem,这个方式权限比较高。另外用户可以自定义Name
然后鼠标左键点击serviceInstaller1,查看右下角的属性,并进行编辑,用户可以编辑服务的名称ServiceName、显示名称DisplayName、描述Description等属性。
设置弹窗,右键项目添加类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace MyService
{
class Interop
{
public static IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
public static void ShowMessageBox(string message, string title)
{
int resp = 0;
WTSSendMessage(
WTS_CURRENT_SERVER_HANDLE,
WTSGetActiveConsoleSessionId(),
title, title.Length,
message, message.Length,
0, 0, out resp, false);
}
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int WTSGetActiveConsoleSessionId();
[DllImport("wtsapi32.dll", SetLastError = true)]
public static extern bool WTSSendMessage(
IntPtr hServer,
int SessionId,
String pTitle,
int TitleLength,
String pMessage,
int MessageLength,
int Style,
int Timeout,
out int pResponse,
bool bWait
);
}
}
在主函数里调用
Interop.ShowMessageBox(“This a message from AlertService.”, “AlertService Message”);
至此C#服务程序配置完成
5.服务的发布和卸载
注册:C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe 工程路径\bin\Debug\WmsWService.exe
注销:C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /u 工程路径\bin\Debug\WmsWService.exe
WIN+R输入cmd打开命令行进行注册
WIN+R输入services.msc查看服务
右键启动服务
弹窗出现