Модераторы: Partizan, gambit
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Моя служба должна запустить форму, Моя служба должна запустить форму 
V
    Опции темы
AndyR
Дата 4.3.2010, 16:02 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 3
Регистрация: 4.3.2010

Репутация: нет
Всего: нет



Вот код 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? Я думаю, что именно в этом причина, что моя форма не работает как должна.
PM MAIL   Вверх
Freak_FB
Дата 4.3.2010, 19:10 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Ктулхувед
**


Профиль
Группа: Участник
Сообщений: 296
Регистрация: 13.10.2006

Репутация: 1
Всего: 4



Не скажу точно, почему, но везде говорится, что службы не должны иметь никакого GUI.
Лучше сделать ещё одно приложение, которое будет работать в пользовательской сессии, чтобы оно постоянно следило за состоянием службы, принимало от неё сообщения, выводило пользовательский интерфейс.


--------------------
user posted image
user posted image
Тонет Ктулху, все медведы горят в огне.
Я Креведко, очень страшно сегодня мне.

PM MAIL ICQ Skype GTalk Jabber   Вверх
AndyR
Дата 5.3.2010, 16:11 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 3
Регистрация: 4.3.2010

Репутация: нет
Всего: нет



Спасибо за ответ. Есть ли где-нибудь пример такой реализации?
PM MAIL   Вверх
Freak_FB
Дата 5.3.2010, 16:40 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Ктулхувед
**


Профиль
Группа: Участник
Сообщений: 296
Регистрация: 13.10.2006

Репутация: 1
Всего: 4



Примером не обеспечу, но могу дать направление поиска.
Я, когда делал GUI для управления службой, использовал IPC (interprocess comunication) через .Nеt Remoting.
Remoting относится к 2-му фреймворку, поэтому, если вы пишете под третий или 3.5 - лучше сразу учите WCF.



--------------------
user posted image
user posted image
Тонет Ктулху, все медведы горят в огне.
Я Креведко, очень страшно сегодня мне.

PM MAIL ICQ Skype GTalk Jabber   Вверх
AndyR
Дата 5.3.2010, 18:16 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 3
Регистрация: 4.3.2010

Репутация: нет
Всего: нет



Еще раз спасибо. 
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
mr.DUDA
THandle

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.
Что делать если Вам помогли, но отблагодарить помощника плюсом в репутацию Вы не можете(не хватает сообщений)? Пишите сюда, или отправляйте репорт. Поставим :)
Так же не забывайте отмечать свой вопрос решенным, если он таковым является :)


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, THandle.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Общие вопросы по .NET и C# | Следующая тема »


 




[ Время генерации скрипта: 0.0446 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.