- VisualStudio2022插件的安装及使用-编程手把手系列文章
- pprof-在现网场景怎么用
- C#实现的下拉多选框,下拉多选树,多级节点
- 【学习笔记】基础数据结构:猫树
很多时候,我们希望服务程序可以直接运行,或者可以响应一些参数,这时候,混合Windows服务和Windows窗体的程序就排上用场了。要实现同时支持Windows服务和Windows窗体,需要在启动的第一步时判断当前运行环境是否为服务模式,可以从以下几个方面进行判断:
如果上述条件都不成立,就进入窗体模式,或者是响应一些其他的命令行参数,比如安装[/i]、卸载服务[/u]等.
项目需要添加下面的组件引用:
项目包含的类文件:
各个类的代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Diagnostics; 4 using System.IO; 5 using System.Runtime.InteropServices; 6 using System.ServiceProcess; 7 using System.Windows.Forms; 8 9 namespace WindowsServiceFormHybridSample 10 { 11 internal static class Program 12 { 13 public const string SERVICE_NAME = "WindowsServiceFormHybridSample"; 14 15 [STAThread] 16 static void Main(string[] args) 17 { 18 //本应用程序为Windows服务和Windows窗体混合的模式 19 //如果启动参数为/S,则进入Windows服务模式,否则进入Windows窗体模式 20 //如果当前账户名称为SYSTEM,则进入Windows服务模式,否则进入Windows窗体模式 21 22 //var serviceMode = args.Length > 0 && args[0].Equals("/S", StringComparison.OrdinalIgnoreCase); 23 var serviceMode = Environment.UserName.Equals("SYSTEM", StringComparison.OrdinalIgnoreCase); 24 25 try 26 { 27 if (serviceMode) 28 { 29 //开启Windows服务模式,切勿弹出消息框 30 ServiceBase.Run(new MainService()); 31 return; 32 } 33 34 //开启Windows窗体模式 35 Application.EnableVisualStyles(); 36 Application.SetCompatibleTextRenderingDefault(false); 37 38 if (args.Length == 0) 39 { 40 //打开窗体 41 using (var form = new MainForm()) 42 { 43 Application.Run(form); 44 } 45 46 return; 47 } 48 49 //处理命令行参数 50 Program.ParseArgs(args); 51 } 52 catch (Exception ex) 53 { 54 if (serviceMode) 55 { 56 //写入错误日志 57 } 58 else 59 { 60 MessageBox.Show(ex.ToString()); 61 } 62 } 63 } 64 65 private static void ParseArgs(string[] args) 66 { 67 var argInstall = 0; 68 var argUninstall = 0; 69 var argSilent = 0; 70 var argOthers = 0; 71 72 foreach (var arg in args) 73 { 74 var temp = arg.Replace('/', '-').ToUpper(); 75 76 switch (temp) 77 { 78 case "-I": 79 argInstall = 1; 80 break; 81 case "-U": 82 argUninstall = 1; 83 break; 84 case "-S": 85 argSilent = 1; 86 break; 87 default: 88 argOthers = 1; 89 break; 90 } 91 } 92 93 if (argOthers == 1) 94 { 95 MessageBox.Show(Program.SERVICE_NAME + "支持的命令行参数:\r\n\r\n/i\t安装更新服务\r\n/u{2}卸载更新服务\r\n/s\t静默模式"); 96 } 97 else 98 { 99 int value = argInstall + argUninstall; 100 101 switch (value) 102 { 103 case 0: 104 MessageBox.Show("需要指定[/i]或者[/u]参数。"); 105 break; 106 case 2: 107 MessageBox.Show("不能同时指定[/i]和[/u]参数。"); 108 break; 109 default: 110 if (argInstall == 1) 111 { 112 Program.InstallServiceA(false, argSilent == 1); 113 } 114 else 115 { 116 Program.InstallServiceB(true, argSilent == 1); 117 } 118 119 break; 120 } 121 } 122 } 123 124 /// <summary> 125 /// 调用.NET Framework框架的InstallUtil.exe工具安装卸载服务,需要项目中包含服务安装类ServiceInstaller.cs 126 /// </summary> 127 private static void InstallServiceA(bool uninstall = false, bool slient = false) 128 { 129 try 130 { 131 var fileName = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "InstallUtil.exe"); 132 var args = string.Format("{0}\"{1}\"", uninstall ? "/U " : string.Empty, Application.ExecutablePath); 133 134 using (var process = Process.Start(new ProcessStartInfo(fileName, args) { WindowStyle = ProcessWindowStyle.Hidden })) 135 { 136 process.WaitForExit(10000); 137 } 138 139 if (uninstall) 140 { 141 return; 142 } 143 144 fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "sc.exe"); 145 args = string.Format("start \"{0}\"", Program.SERVICE_NAME); 146 147 using (var process = Process.Start(new ProcessStartInfo(fileName, args) { WindowStyle = ProcessWindowStyle.Hidden })) 148 { 149 process.WaitForExit(10000); 150 } 151 } 152 catch (Exception ex) 153 { 154 MessageBox.Show(ex.ToString()); 155 } 156 } 157 158 /// <summary> 159 /// 调用操作系统的sc.exe工具安装卸载服务 160 /// </summary> 161 private static void InstallServiceB(bool uninstall = false, bool slient = false) 162 { 163 try 164 { 165 var fileName = Path.Combine(Environment.SystemDirectory, "sc.exe"); 166 var argsList = new List<string>(); 167 168 if (!uninstall) 169 { 170 argsList.Add(string.Format("create {0} binPath= \"{1}\" start= auto", Program.SERVICE_NAME, Application.ExecutablePath)); 171 argsList.Add(string.Format("start {0}", Program.SERVICE_NAME)); 172 } 173 else 174 { 175 argsList.Add(string.Format("stop {0}", Program.SERVICE_NAME)); 176 argsList.Add(string.Format("delete {0}", Program.SERVICE_NAME)); 177 } 178 179 foreach (var args in argsList) 180 { 181 using (var process = Process.Start(new ProcessStartInfo(fileName, args) { WindowStyle = ProcessWindowStyle.Hidden })) 182 { 183 process.WaitForExit(10000); 184 } 185 } 186 } 187 catch (Exception ex) 188 { 189 MessageBox.Show(ex.ToString()); 190 } 191 } 192 } 193 }
1 using System; 2 using System.ServiceProcess; 3 4 namespace WindowsServiceFormHybridSample 5 { 6 internal class MainService : ServiceBase 7 { 8 public MainService() 9 { 10 base.ServiceName = Program.SERVICE_NAME; 11 } 12 13 protected override void OnStart(string[] args) 14 { 15 try 16 { 17 //这里最好执行异步的方法 18 //否则会导致Windows的服务启动超时 19 20 //与MainForm执行相同的方法 21 MainWorker.Start(); 22 } 23 catch (Exception ex) 24 { 25 //写入错误日志 26 } 27 } 28 29 protected override void OnStop() 30 { 31 try 32 { 33 MainWorker.Stop(); 34 } 35 catch (Exception ex) 36 { 37 //写入错误日志 38 } 39 } 40 } 41 }
1 using System; 2 using System.Windows.Forms; 3 4 namespace WindowsServiceFormHybridSample 5 { 6 public partial class MainForm : Form 7 { 8 public MainForm() 9 { 10 this.InitializeComponent(); 11 this.button1.Text = "启动服务"; 12 } 13 14 private void button1_Click(object sender, EventArgs e) 15 { 16 //与MainService执行相同的方法 17 try 18 { 19 if (this.button1.Text == "启动服务") 20 { 21 MainWorker.Start(); 22 this.button1.Text = "停止服务"; 23 return; 24 } 25 26 MainWorker.Stop(); 27 this.button1.Text = "启动服务"; 28 } 29 catch (Exception ex) 30 { 31 MessageBox.Show(ex.ToString()); 32 } 33 } 34 } 35 }
1 using System; 2 using System.Threading; 3 using System.Threading.Tasks; 4 5 namespace WindowsServiceFormHybridSample 6 { 7 internal class MainWorker 8 { 9 private static MainWorker _instance; 10 private static CancellationTokenSource _cancellationTokenSource; 11 12 private bool _isBusy; 13 14 public bool IsBusy { get => this._isBusy; } 15 16 static MainWorker() 17 { 18 MainWorker._instance = new MainWorker(); 19 } 20 21 private async void DoWork(CancellationToken cancellationToken) 22 { 23 this._isBusy = true; 24 25 while (!cancellationToken.IsCancellationRequested) 26 { 27 await Task.Delay(1000); 28 29 //其他耗时任务 30 } 31 32 this._isBusy = false; 33 } 34 35 public static void Start() 36 { 37 if (MainWorker._instance.IsBusy) 38 { 39 throw new Exception("服务正在运行中。"); 40 } 41 42 MainWorker._cancellationTokenSource = new CancellationTokenSource(); 43 MainWorker._instance.DoWork(_cancellationTokenSource.Token); 44 } 45 46 public static void Stop() 47 { 48 if (MainWorker._cancellationTokenSource != null) 49 { 50 MainWorker._cancellationTokenSource.Cancel(); 51 } 52 } 53 } 54 }
1 using System.ComponentModel; 2 using System.Configuration.Install; 3 using System.ServiceProcess; 4 5 namespace WindowsServiceFormHybridSample 6 { 7 [RunInstaller(true)] 8 public class ServiceInstaller : Installer 9 { 10 public ServiceInstaller() 11 { 12 var ServiceProcessInstaller = new ServiceProcessInstaller() 13 { 14 Account = ServiceAccount.LocalSystem 15 }; 16 17 var ServiceInstaller = new System.ServiceProcess.ServiceInstaller 18 { 19 ServiceName = Program.SERVICE_NAME, 20 StartType = ServiceStartMode.Automatic 21 }; 22 23 base.Installers.AddRange(new Installer[] { ServiceProcessInstaller, ServiceInstaller }); 24 } 25 } 26 }
最后此篇关于C#开发一个混合Windows服务和Windows窗体的程序的文章就讲到这里了,如果你想了解更多关于C#开发一个混合Windows服务和Windows窗体的程序的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我需要一些说明。我可以直接写入 /dev/port 以直接访问并行端口并且它工作正常(我可以打开插入端口连接器的 LED)。但是,我想我可以用 /dev/mem 做同样的事情? (http://tld
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我使用 Visual C++ 和 Win32 API 学习了 Windows 编程。如今,似乎大多数应用程序都是使用 C# 在 .NET 中开发的。我知道大多数时候 native 代码和托管代码之间没
请耐心等待。我正在制作一个 java 控制台,类似于此处找到的 DragonConsole https://code.google.com/p/dragonconsole/ 。一切都按计划进行,但我想
关闭。这个问题需要更多 focused .它目前不接受答案。 想要改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭5年前。 Improve this que
Django 的开发服务器表现得很奇怪。访问它的浏览器在加载时卡住,任何退出它的尝试都不起作用。当我点击 control c看似相当,但实际上仍在运行。让它退出的唯一方法是重新启动我的电脑,这很令人沮
我正在使用 Flash Develop,并且创建了一个 ActionScript 3.0 项目。它启动并读取一个 xml 文件,其中包含图像的 url。我已将 url 保留在与 swf 相同的文件夹中
是否可以根据其 website 上提供的规范开发 AUTOSAR BSW 堆栈(例如用于 CAN 通信)?不购买任何昂贵的供应商工具?可以遵循哪些步骤?我被要求探索这种可能性。 最佳答案 是和否。工具
有人知道如何用音频文件的内容覆盖 iPhone 麦克风吗? 想象一个场景,您正在通话,并且想要播放一些简短的音频让其他人听到。 因此,有必要将麦克风(硬件)置于保持状态,并使用委托(delegate)
我遇到了这个问题,我的应用程序出现 EXC_BAD_ACCESS 错误并卡住/停止。我使用模拟器的“向左旋转”和“向右旋转”选项来模拟方向变化行为。导致此错误的可能原因有哪些?由于我没有获得有关错误的
我有超过 1 台 Mac,我想在所有这些 Mac 上进行开发。我知道我需要在每台机器上同步我的手机,但这是我遇到的最小的问题。看起来我无法在手机上运行应用程序,除了在其中之一上开发的应用程序。 是否有
在手机上测试时,我的应用程序在特定点崩溃。控制台显示此消息 Tue Jan 27 15:47:14 unknown SpringBoard[22] : Application com.myprof.
我有一个案例,我从服务器获取信息。我的应用程序有一个选项卡栏和导航按钮。我希望应用程序显示进度指示器并禁用所有其他控件,以便用户在从服务器提取数据时无法跳转。我怎样才能实现这个目标? 我想到的一种方法
有时,当我尝试“构建”/编译下载的源代码时,我会收到以下警告: ld: warning: directory '/Volumes/Skiiing2/CD/ViewBased/Unknown Path/
我无法在 Apple 文档中找到关于开发和分发配置之间差异的明确解释。我目前正在使用开发配置在我的 iPhone 上进行开发和测试。我打算将该应用程序分发到我的 Beta 测试中,我想知道: 我需要使
我在使用 SharePoint 时遇到的最大挑战之一是它不能很好地适应典型的项目环境,其中至少包含开发和生产环境。我遇到的最多的问题是内容和列表是如此紧密地耦合在一起,以至于如果不在生产环境中执行内容
我失败了fist step让 Eclipse(对我来说是全新的)为 ARM 开发做好准备。 我在 Windows 10 中安装了 Eclipse。我想我应该安装 xpm,但我不知道在哪里输入此命令:
首先,我告诉你-我是编码新手 我正在使用vs代码来学习c++,它不会产生像dev c++或codeblocks这样的调试器。我看了一些视频,其中我们必须编辑json文件,这对于初学者来说非常复杂。有人
我失败了fist step让 Eclipse(对我来说是全新的)为 ARM 开发做好准备。 我在 Windows 10 中安装了 Eclipse。我想我应该安装 xpm,但我不知道在哪里输入此命令:
我开发了一个 Ionic 应用程序(iOS 和 Android 的混合)。我有 Xcode 8.3.3 并购买了一年的 Apple Developer Program 订阅。 我不想测试我的应用并将其
我是一名优秀的程序员,十分优秀!