admin管理员组文章数量:1306209
In .NET Framework 4.6.2, if I double-click an exe that's registered as a Windows service, I see this message:
Great! Prevents bad things from happening.
Now I'm on .NET 8 and I've written a Windows service that is a BackgroundTask with a Worker... how can I emulate this same behavior where someone tries to run it directly from the EXE? I want to prevent the thing from running unless it's a service. Can this be done?
In .NET Framework 4.6.2, if I double-click an exe that's registered as a Windows service, I see this message:
Great! Prevents bad things from happening.
Now I'm on .NET 8 and I've written a Windows service that is a BackgroundTask with a Worker... how can I emulate this same behavior where someone tries to run it directly from the EXE? I want to prevent the thing from running unless it's a service. Can this be done?
Share Improve this question asked Feb 3 at 13:25 FoxScullyFoxScully 635 bronze badges 6 | Show 1 more comment1 Answer
Reset to default 4This question is practically important.
This problem and related problems can be solved by using the property System.Environment.UserInteractive
.
If the value of this property is true
during runtime, the application was loaded and started as a normal application of any kind, for example, via the system Shell. Otherwise, it was started as a service, that is, loaded and started by the service controller.
In particular, you can do even better: you can create an application that can be started and work correctly in both ways. In the interactive mode, it can even execute some windowed UI. Also, if you share most of the code between interactive and service mode, you can debug this code the same way you do it for the normal (interactive application), which is a lot easier.
For example, you can check the property in your Main
and conditionally execute one of two branches:
class Program {
// ...
static void Main() {
if (System.Environment.UserInteractive)
StartUI();
else
StartService();
} //Main
}
本文标签:
版权声明:本文标题:C# .NET 8 - How to show a warning if the EXE is just double-clicked? Only want it to run as a service - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741818703a2399231.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
Environment.UserInteractive
in your app's entry-point? (it should befalse
when running as a service) – Marc Gravell Commented Feb 3 at 13:35System.Window.Forms
or WPF in your application. With WPF, you may need a special approach, without app.xaml, to start withMain
, but this is pretty simple. I can explain it, too. – Sergey A Kryukov Commented Feb 3 at 14:05