using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.ServiceProcess;
using System.Diagnostics;

namespace Core.Ms.ServerListenerTray
{
    public partial class Form1 : Form
    {
        ServiceController serviceCtl = new ServiceController();

        public Form1()
        {
            InitializeComponent();

            serviceCtl.ServiceName = "Core.Mes.ServerListener";
            serviceCtl.MachineName = ".";
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                MenuStrip1.Show();
            }
            else
            {
                MenuStrip1.Hide();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Hide();
            this.Visible = false;
        }

        private void CheckListenerStatus()
        {
            serviceCtl.Refresh();
            notifyIcon1.Visible = true;
            notifyIcon1.Text = string.Format("MES 监控服务 [{0}]", serviceCtl.Status == ServiceControllerStatus.Running ? "正在运行" : "停止");
            notifyIcon1.BalloonTipText = notifyIcon1.Text;
            notifyIcon1.Icon = (serviceCtl.Status == ServiceControllerStatus.Stopped) ? Properties.Resources.stop : Properties.Resources.play;
            Debug.Print(DateTime.Now.ToString("hh:MM:ss") + " " + serviceCtl.Status.ToString());
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            CheckListenerStatus();
        }

        private void 启动监控服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                serviceCtl.Refresh();
                if (serviceCtl.Status != ServiceControllerStatus.Running)
                {
                    serviceCtl.Start();
                }
            }
            catch { }
        }

        private void 停止监控服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                serviceCtl.Refresh();
                if (serviceCtl.Status != ServiceControllerStatus.Stopped)
                {
                    serviceCtl.Stop();
                }
            }
            catch { }
        }

        private void 退出托盘ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            notifyIcon1.Visible = false;
            this.Close(); 
        }


    }
}
