[英]How can I create a windows application that should run with admin rights in .Net C# without prompting UAC again and again?
[英]How can I create a Windows application that can run with a GUI *or* as a Windows service in C#?
我想使用C#創建一個應用程序...:
可以使用GUI作為Windows應用程序運行(它將指示進度,狀態等)
要么
無需Windows即可作為Windows服務運行
可能嗎? 有人可以讓我開始嗎?
我猜這是我可以創建一個Windows服務,然后創建一個單獨的GUI應用程序,該應用程序可以輪詢Windows服務以從中獲取數據(進度,狀態等)。
在這種情況下,如何從GUI應用程序從Windows服務中獲取數據?
我正在做的事情與您要的類似。 我對它進行了編程,以便將命令行參數“ / form”發送給可執行文件時,它將彈出一個Windows窗體,而不是作為服務運行。
就運行后台作業本身而言,在兩種情況下,您都需要執行某種線程處理(也許使用計時器)來完成工作並異步將狀態報告給表單。 關於創建線程GUI應用程序,這將是一個完全不同的討論主題。
“表單或服務”代碼如下所示:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
private static void Main(string[] args)
{
if (args.Length > 0 && args[0] == "/form")
{
var form = new MainForm();
Application.Run(form);
return;
}
var ServicesToRun = new ServiceBase[]
{
new BackgroundService()
};
ServiceBase.Run(ServicesToRun);
}
}
我從未做過可以作為Windows服務或GUI運行的應用程序,但是我們有很多應用程序可以使用編譯器標志在控制台應用程序和Windows服務之間進行切換。 (我剛剛看到了cmd行arg的答案-可能更好!)
然后,我們通常只使用編譯器標志在兩者之間進行切換。 這是一個示例...我並未完全考慮到這一點,但這可能會為您提供一個起點:
#define RUN_AS_SERVICE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.ServiceProcess;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
#if RUN_AS_SERVICE
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[]
{
new MyService()
};
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#else
// Run as GUI
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
#endif
}
}
public class MyService : ServiceBase
{
protected override void OnStart(string[] args)
{
// Start your service
}
protected override void OnStop()
{
// Stop your service
}
}
}
在庫中構建實際的應用程序。 然后,您可以添加所需的任何UI(由於服務不是真正的UI,我可以這樣說)。 只要您將該應用程序視為Windows應用程序和服務應用程序,就可以開發兩個應用程序。 如果您將應用程序視為要解決的業務問題,那么您將想到Windows窗體UI和服務UI,這對於您的需求而言更為合理。
盡管這聽起來很理智,但您會驚訝於有多少應用程序需要完全覆蓋才能成為其他UI類型。 感謝你的提問。 它使我確信我正在寫這本書。 :-)
您應該選擇后者。 創建您的服務,然后創建一個單獨的GUI應用程序。 框架中已經為您提供了用於執行所有這些操作的大多數管道。 看一下ServiceController類。
我看到了這個主題,可能會為您提供更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.