Вот код service1. При вызове открывается блокнот (то же и с моей формой) в task manager на закладке process. В этом случае, при запуске формы из сервиса, я вижу процесс в task manager на закладке процессы, который я запустил. Но на закладке application его нет.
| Код | using System; using System.ServiceProcess; using System.Windows.Forms; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Drawing; using System.Collections;
namespace InteractiveService {
public class Service1 : System.ServiceProcess.ServiceBase {
private System.Diagnostics.EventLog eventLog1; /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null;
public enum State { SERVICE_STOPPED = 0x00000001, SERVICE_START_PENDING = 0x00000002, SERVICE_STOP_PENDING = 0x00000003, SERVICE_RUNNING = 0x00000004, SERVICE_CONTINUE_PENDING = 0x00000005, SERVICE_PAUSE_PENDING = 0x00000006, SERVICE_PAUSED = 0x00000007, }
public Service1() { // This call is required by the Windows.Forms Component Designer. InitializeComponent();
// TODO: Add any initialization after the InitComponent call
//if (!System.Diagnostics.EventLog.SourceExists("KepWareConnectMySQL")) //{ // System.Diagnostics.EventLog.CreateEventSource("KepWareConnectMySQL", "Application"); //}
//eventLog1.Source = "KepWareConnectMySQL"; //eventLog1.Log = "Application"; }
// The main entry point for the process static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun;
// More than one user Service may run within the same process. To add // another service to this process, change the following line to // create a second service object. For example, // // ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()}; // ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.eventLog1 = new System.Diagnostics.EventLog(); ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit(); // // eventLog1 // this.eventLog1.Log = "Application"; this.eventLog1.Source = "InteractiveService"; // // Service1 // this.CanHandlePowerEvent = true; this.CanHandleSessionChangeEvent = true; this.CanPauseAndContinue = true; this.CanShutdown = true; this.ServiceName = "InteractiveService"; // ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
}
/// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); }
/// <summary> /// Set things in motion so your service can do its work. /// </summary> protected override void OnStart(string[] args) { try { // TODO: Add code here to start your service. InteractiveService.MakeServiceInteractive(); eventLog1.WriteEntry("Service Started Succesfully");
//MessageBox.Show("Service Started Succesfully"); startprc(@"C:\WINDOWS\system32\notepad.exe"); //startprc(@"c:\SAP\FormKepWareAndMySQL.exe"); eventLog1.WriteEntry("Started Process Succesfully"); } catch (System.Exception ex) { eventLog1.WriteEntry(String.Format("Service OnStart ERROR :'" + ex.Message + "'")); } }
/// <summary> /// Stop this service. /// </summary> protected override void OnStop() { // TODO: Add code here to perform any tear-down necessary to stop your service. eventLog1.WriteEntry("Service Stoped Succesfully"); Killprc("notepad"); //Killprc("FormKepWareAndMySQL"); } protected override void OnContinue() { eventLog1.WriteEntry("Service work started after pause succesfully"); } protected override void OnPause() { eventLog1.WriteEntry("Service work paused succesfully"); } private void startprc(string prcName) { try { //'Using whole path is required (you could use opendialog to find) eventLog1.WriteEntry(String.Format("startprc :'" + prcName + "'")); ShellLib.ShellExecute shellExecute = new ShellLib.ShellExecute(); shellExecute.Path = prcName; shellExecute.Execute(); } catch (System.Exception ex) { eventLog1.WriteEntry(String.Format("Service work start process ERROR :'" + ex.Message + "'")); //MsgBox(ex.Source & ": " & ex.Message) } // Return 0 } private void Killprc(string processName) { //'Prc is short for process...you could have called it anything foreach (Process p in System.Diagnostics.Process.GetProcessesByName(processName)) { try { p.Kill(); p.WaitForExit(); // possibly with a timeout eventLog1.WriteEntry(String.Format("Process Kill Succesfully :'" + processName + "'")); } catch (InvalidOperationException invalidException) { // process has already exited - might be able to let this one go eventLog1.WriteEntry(String.Format("process has already exited - might be able to let this one go, InvalidOperationException :'" + invalidException + "'")); } catch (System.Exception ex) { eventLog1.WriteEntry(String.Format("Service work start process, System.Exception :'" + ex.Message + "'")); } } } } }
|
Во втором случае, при запуске этого же кода из формы, я вижу процесс на обоих закладках в task manager.
| Код | using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace WinTester2 { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.GroupBox grpLaunchApp; private System.Windows.Forms.Button btnExploreFolder; private System.Windows.Forms.Button btnFindInFolder; private System.Windows.Forms.Button btnEditBmp; private System.Windows.Forms.Button btnShowBmp; private System.Windows.Forms.Button btnOpenExe; private System.Windows.Forms.GroupBox grpFileOp; private System.Windows.Forms.Button btnCopy; private System.Windows.Forms.Button btnMove; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.Button btnClearList; private System.Windows.Forms.Button btnAddFile; private System.Windows.Forms.GroupBox grpRecentDocs; private System.Windows.Forms.GroupBox grpPrinter; private System.Windows.Forms.Button btnOpenPrinter; private System.Windows.Forms.Button btnShowProperties; private System.Windows.Forms.Button btnTestPage; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } private void btnOpenExe_Click(object sender, System.EventArgs e) { ShellLib.ShellExecute shellExecute = new ShellLib.ShellExecute(); //shellExecute.Path = @"c:\SAP\FormKepWareAndMySQL.exe"; shellExecute.Path = @"C:\WINDOWS\system32\notepad.exe"; shellExecute.Execute(); } } }
|
Как мне запустить форму из сервиса, чтобы она появилась на закладке application? Я думаю, что именно в этом причина, что моя форма не работает как должна. |