仅当我连接到互联网时才能启动Windows服务 [英] to start a Windows Service only when I am connected to the internet

查看:81
本文介绍了仅当我连接到互联网时才能启动Windows服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个Windows应用程序,当我单击Windows窗体中的监视器"按钮时,它将监视我的Internet连接状态.

我只是想知道,是否可以创建一个服务应用程序,该应用程序在我连接到互联网时会自动启动,而在断开连接时会停止.

如果我没看错,我认为服务程序可以在计算机打开时在后台运行,并且可以用来监视Internet的运行状态.因此,如果状态变为"UP",则可以使该服务执行某些功能,当状态变为"Down"时,该服务应停止其操作.

请帮助我.

谢谢,
Perk

I developed a windows application that will monitor the status of my internet connection when I click on the "Monitor" button in my windows form.

I just wanted to know that, is it possible to create a service application that will start automatically whenever I connect to internet and stops when I am disconnected.

If I am not wrong, I think the service programs runs in the background when the computer is ON and can be made to monitor the internet operational status; so that if the status turns "UP", then the service can be made to perform some functions and when it turns "Down" then the service should stop its action.

Kindly help me with this.

Thanks,
Perk

推荐答案

如何将其作为Windows服务?如果我已连接到Internet,则应在其中调用startMonitor()函数,而当我断开连接时,应在其中调用closeEverything()函数.请帮帮我.

How do I make this as a windows service; where the startMonitor() function should be called if I am connected to internet and closeEverything() function should be called when I am disconnected. Kindly help me out.

using System;
using System.Runtime;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

using System.Net;
using System.Net.NetworkInformation;


namespace NetworkTracer
{
    public partial class Tracer : Form
    {        
        private Timer _timer;
        private DateTime _startTime = DateTime.MinValue;
        IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
        IPGlobalStatistics ipstat = null;
        Decimal start_r_packets;
        Decimal end_r_packets;
        NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
        NetworkInterface adapter;

        long start_received_bytes;
        long start_sent_bytes;
        long end_received_bytes;
        long end_sent_bytes;

        public Tracer()
        {
            InitializeComponent();

            btnMonitor.Enabled = true;
            btnCancel.Enabled = false;
            btnCancel.Text = "";            
            btnCancel.BackColor = Color.Transparent;
            txtboxInfo.BackColor = Color.White;

            _timer = new Timer();           
            _timer.Tick += new EventHandler(timerTicker);
        }


        protected void startMonitor(object sender, EventArgs e)
        {
            txtboxInfo.BackColor = Color.Wheat;
            btnMonitor.BackColor = Color.Transparent;
            btnMonitor.FlatAppearance.BorderSize = 0;
            btnCancel.BackColor = Color.Beige;
            Tracer.ActiveForm.BackColor = Color.Firebrick;
            btnMonitor.Text = "";
            btnCancel.Text = "Cancel";

            _startTime = DateTime.Now;                        
            _timer.Start();                        
            btnMonitor.Enabled = false;
            btnCancel.Enabled = true;
            ipstat = properties.GetIPv4GlobalStatistics();
           
            getConnectionInfo();
        }
        
        protected void getConnectionInfo()
        {
            try
            {              
                string myHost = System.Net.Dns.GetHostName();
                IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(myHost);
                IPAddress[] addr = ipEntry.AddressList;

                if (addr.Length > 0)
                {
                    start_r_packets = Convert.ToDecimal(ipstat.ReceivedPackets);

                    txtboxInfo.Text = "";
                    txtboxInfo.Text += "IP Address: " + addr[addr.Length - 1].ToString() + Environment.NewLine;
                    
                    adapter = fNetworkInterfaces[0];

                    start_received_bytes = fNetworkInterfaces[0].GetIPv4Statistics().BytesReceived;
                    start_sent_bytes = fNetworkInterfaces[0].GetIPv4Statistics().BytesSent;                   

                    txtboxInfo.Text += Environment.NewLine + "Name: " + adapter.Name + Environment.NewLine;
                    txtboxInfo.Text += Environment.NewLine + "Description: " + adapter.Description + Environment.NewLine;
                    txtboxInfo.Text += Environment.NewLine + "Network Type: " + adapter.NetworkInterfaceType + Environment.NewLine;
                    txtboxInfo.Text += Environment.NewLine + "Speed: " + adapter.Speed / 1000000 + " (Mbps)" + Environment.NewLine;
                    txtboxInfo.Text += Environment.NewLine + "Operational Status: " + adapter.OperationalStatus + Environment.NewLine;

                    txtboxInfo.Text += Environment.NewLine + "Received: " + start_received_bytes.ToString() + Environment.NewLine;
                    start_received_bytes = (start_received_bytes / 1048576 * 100000) / 100000;
                    txtboxInfo.Text += "Received (in MB): " + start_received_bytes.ToString() + Environment.NewLine;
                    txtboxInfo.Text += Environment.NewLine + "Sent: " + start_sent_bytes.ToString() + Environment.NewLine;                    
                    start_sent_bytes = (start_sent_bytes / 1048576 * 100000) / 100000;                                        
                    txtboxInfo.Text += "Sent (in MB): " + start_sent_bytes.ToString() + Environment.NewLine;
                    
                    txtboxInfo.Text += Environment.NewLine + "Starting Received Packets: " + start_r_packets.ToString() + Environment.NewLine;                                        
                }                                                
            }
            catch (Exception ex)
            {
                txtboxInfo.Text = "Error !" + Environment.NewLine + ex.Message.ToString();
                _timer.Stop();
                lblTime.Text = "";                
                btnCancel.Enabled = false;
                btnMonitor.Enabled = false;
                btnCancel.Text = "";
                btnMonitor.Text = "";
                btnCancel.BackColor = Color.Transparent;
            }
        }

        protected void closeEverything(object sender, EventArgs e)
        {
            try
            {
                _timer.Stop();
                btnCancel.Enabled = false;
                btnMonitor.Enabled = true;
                txtboxInfo.BackColor = Color.White;
                btnMonitor.BackColor = Color.Red;
                btnCancel.BackColor = Color.Transparent;
                btnMonitor.FlatAppearance.BorderSize = 1;
                btnCancel.Text = "";
                btnMonitor.Text = "Monitor";
                Tracer.ActiveForm.BackColor = Color.Teal;

                txtboxInfo.Text = lblTime.Text + Environment.NewLine;

                ipstat = properties.GetIPv4GlobalStatistics();
                end_r_packets = Convert.ToDecimal(ipstat.ReceivedPackets);

                txtboxInfo.Text += Environment.NewLine + "Starting Received Packets: " + start_r_packets.ToString() + Environment.NewLine;
                txtboxInfo.Text += "  Ending Received Packets: " + end_r_packets.ToString() + Environment.NewLine;
                end_r_packets = end_r_packets - start_r_packets;
                txtboxInfo.Text += "Total Received Packets: " + end_r_packets.ToString() + Environment.NewLine;

                end_received_bytes = fNetworkInterfaces[0].GetIPv4Statistics().BytesReceived;
                end_sent_bytes = fNetworkInterfaces[0].GetIPv4Statistics().BytesSent;
                end_received_bytes = (end_received_bytes / 1048576 * 100000) / 100000;
                end_sent_bytes = (end_sent_bytes / 1048576 * 100000) / 100000;

                txtboxInfo.Text += Environment.NewLine + "Received Start (in MB): " + start_received_bytes.ToString() + Environment.NewLine;                
                txtboxInfo.Text += "  Received End (in MB): " + end_received_bytes.ToString() + Environment.NewLine;
                txtboxInfo.Text += "Received Total (in MB): " + (end_received_bytes - start_received_bytes).ToString() + Environment.NewLine;
                txtboxInfo.Text += Environment.NewLine + "Sent Start (in MB): " + start_sent_bytes.ToString() + Environment.NewLine;
                txtboxInfo.Text += "  Sent End (in MB): " + end_sent_bytes.ToString() + Environment.NewLine;                
                txtboxInfo.Text += "Sent Total (in MB): " + (end_sent_bytes - start_sent_bytes).ToString() + Environment.NewLine;

                writetoFile();

                lblTime.Text = "";
            }
            catch (Exception ex)
            {
                txtboxInfo.Text = "Error !" + Environment.NewLine + ex.Message.ToString();
                _timer.Stop();
                lblTime.Text = "";                
                btnCancel.Enabled = false;
                btnMonitor.Enabled = false;
                btnCancel.Text = "";
                btnMonitor.Text = "";
                btnMonitor.BackColor = Color.Transparent;
                btnMonitor.FlatAppearance.BorderSize = 0;
            }
        }

        protected void writetoFile()
        {
            string path_file = @"C:\\Documents and Settings\\user\\Desktop\\Test Tracer.txt";
            string empty_line = "===============================================================";
            if (System.IO.File.Exists(path_file))
            {
                System.IO.File.AppendAllText(path_file, empty_line + Environment.NewLine + "Connection opened: " + _startTime + Environment.NewLine + "Connection Closed: " + DateTime.Now.ToString() + Environment.NewLine + Environment.NewLine + txtboxInfo.Text + Environment.NewLine);
            }
        }

        protected void timerTicker(object sender, EventArgs e)
        {
            var timeSinceStartTime = DateTime.Now - _startTime;
            timeSinceStartTime = new TimeSpan(timeSinceStartTime.Hours,
                                              timeSinceStartTime.Minutes,
                                              timeSinceStartTime.Seconds);                        
            lblTime.Text = "Time: " + timeSinceStartTime.ToString();

            if (adapter.OperationalStatus.ToString().ToUpper() != "UP")
            {
                MessageBox.Show("Connection Lost!");
                closeEverything(this, e);
            }
        }
    }
}


创建Windows服务,并使其在线程上运行,然后该线程检查Internet连接以及是否已连接监视您的应用程序.您可以使用以下Wininet.dll来检测是否已连接Internet.

Create a windows service and let it run on a thread and the thread check internet connectivity and if connected monitor your app. You can use the following Wininet.dll to detect internet connected or not.

//Creating the extern function…
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState( int out Description, int ReservedValue ) ;

//Creating a function that uses the API function…
public static bool IsConnectedToInternet( )
{

int Desc ;
return InternetGetConnectedState( out Desc, 0 ) ;

}



您会获得许多有关在谷歌搜索上构建Windows Service的示例.



You get lot of examples on building Windows Service on googling.


此处是代码的修改版本,它将确定已连接且可运行的适配器.

Here is a modified version of the code which will determine the adapter that is connected and operational.

using System;
using System.Runtime;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

using System.Net;
using System.Net.NetworkInformation;


namespace NetworkTracer
{
    public partial class Tracer : Form
    {        
        private Timer _timer;
        private DateTime _startTime = DateTime.MinValue;
        IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
        IPGlobalStatistics ipstat = null;
        Decimal start_r_packets;
        Decimal end_r_packets;
        NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
        NetworkInterface adapter;

        long start_received_bytes;
        long start_sent_bytes;
        long end_received_bytes;
        long end_sent_bytes;

        public Tracer()
        {
            InitializeComponent();

            btnMonitor.Enabled = true;
            btnCancel.Enabled = false;
            btnCancel.Text = "";            
            btnCancel.BackColor = Color.Transparent;
            txtboxInfo.BackColor = Color.White;

            _timer = new Timer();           
            _timer.Tick += new EventHandler(timerTicker);
        }


        protected void startMonitor(object sender, EventArgs e)
        {
            txtboxInfo.BackColor = Color.Wheat;
            btnMonitor.BackColor = Color.Transparent;
            btnMonitor.FlatAppearance.BorderSize = 0;
            btnCancel.BackColor = Color.Beige;
            Tracer.ActiveForm.BackColor = Color.Firebrick;
            btnMonitor.Text = "";
            btnCancel.Text = "Cancel";

            _startTime = DateTime.Now;                        
            _timer.Start();                        
            btnMonitor.Enabled = false;
            btnCancel.Enabled = true;
            ipstat = properties.GetIPv4GlobalStatistics();
           
            getConnectionInfo();
        }
        

        protected void determineAdapter()
        {
            int val = 0;
            foreach (NetworkInterface test_adapter in fNetworkInterfaces)
            {
                if ((test_adapter.OperationalStatus.ToString().ToUpper() == "UP") && (test_adapter.NetworkInterfaceType.ToString().ToUpper() != "LOOPBACK"))
                    adapter = fNetworkInterfaces[val];

                val++;
            }
        }

        protected void getConnectionInfo()
        {
            try
            {              
                string myHost = System.Net.Dns.GetHostName();
                IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(myHost);
                IPAddress[] addr = ipEntry.AddressList;

                if (addr.Length > 0)
                {
                    start_r_packets = Convert.ToDecimal(ipstat.ReceivedPackets);

                    txtboxInfo.Text = "";
                    txtboxInfo.Text += "IP Address: " + addr[addr.Length - 1].ToString() + Environment.NewLine;

                    determineAdapter();

                    if (adapter != null)
                    {
                      //  adapter = fNetworkInterfaces[0];

                        start_received_bytes = fNetworkInterfaces[0].GetIPv4Statistics().BytesReceived;
                        start_sent_bytes = fNetworkInterfaces[0].GetIPv4Statistics().BytesSent;

                        txtboxInfo.Text += Environment.NewLine + "Name: " + adapter.Name + Environment.NewLine;
                        txtboxInfo.Text += Environment.NewLine + "Description: " + adapter.Description + Environment.NewLine;
                        txtboxInfo.Text += Environment.NewLine + "Network Type: " + adapter.NetworkInterfaceType + Environment.NewLine;
                        txtboxInfo.Text += Environment.NewLine + "Speed: " + adapter.Speed / 1000000 + " (Mbps)" + Environment.NewLine;
                        txtboxInfo.Text += Environment.NewLine + "Operational Status: " + adapter.OperationalStatus + Environment.NewLine;

                        txtboxInfo.Text += Environment.NewLine + "Received: " + start_received_bytes.ToString() + Environment.NewLine;
                        start_received_bytes = (start_received_bytes / 1048576 * 100000) / 100000;
                        txtboxInfo.Text += "Received (in MB): " + start_received_bytes.ToString() + Environment.NewLine;
                        txtboxInfo.Text += Environment.NewLine + "Sent: " + start_sent_bytes.ToString() + Environment.NewLine;
                        start_sent_bytes = (start_sent_bytes / 1048576 * 100000) / 100000;
                        txtboxInfo.Text += "Sent (in MB): " + start_sent_bytes.ToString() + Environment.NewLine;

                        txtboxInfo.Text += Environment.NewLine + "Starting Received Packets: " + start_r_packets.ToString() + Environment.NewLine;
                    }
                    else
                    {
                        throw new ArgumentException("Adapter not set");
                    }

                }                                                
            }
            catch (Exception ex)
            {
                txtboxInfo.Text = "Error !" + Environment.NewLine + ex.Message.ToString();
                _timer.Stop();
                lblTime.Text = "";                
                btnCancel.Enabled = false;
                btnMonitor.Enabled = false;
                btnCancel.Text = "";
                btnMonitor.Text = "";
                btnCancel.BackColor = Color.Transparent;
            }
        }

        protected void closeEverything(object sender, EventArgs e)
        {
            try
            {
                _timer.Stop();
                btnCancel.Enabled = false;
                btnMonitor.Enabled = true;
                txtboxInfo.BackColor = Color.White;
                btnMonitor.BackColor = Color.Red;
                btnCancel.BackColor = Color.Transparent;
                btnMonitor.FlatAppearance.BorderSize = 1;
                btnCancel.Text = "";
                btnMonitor.Text = "Monitor";
                Tracer.ActiveForm.BackColor = Color.Teal;

                txtboxInfo.Text = lblTime.Text + Environment.NewLine;

                ipstat = properties.GetIPv4GlobalStatistics();
                end_r_packets = Convert.ToDecimal(ipstat.ReceivedPackets);

                txtboxInfo.Text += Environment.NewLine + "Starting Received Packets: " + start_r_packets.ToString() + Environment.NewLine;
                txtboxInfo.Text += "  Ending Received Packets: " + end_r_packets.ToString() + Environment.NewLine;
                end_r_packets = end_r_packets - start_r_packets;
                txtboxInfo.Text += "Total Received Packets: " + end_r_packets.ToString() + Environment.NewLine;

                end_received_bytes = fNetworkInterfaces[0].GetIPv4Statistics().BytesReceived;
                end_sent_bytes = fNetworkInterfaces[0].GetIPv4Statistics().BytesSent;
                end_received_bytes = (end_received_bytes / 1048576 * 100000) / 100000;
                end_sent_bytes = (end_sent_bytes / 1048576 * 100000) / 100000;

                txtboxInfo.Text += Environment.NewLine + "Received Start (in MB): " + start_received_bytes.ToString() + Environment.NewLine;                
                txtboxInfo.Text += "  Received End (in MB): " + end_received_bytes.ToString() + Environment.NewLine;
                txtboxInfo.Text += "Received Total (in MB): " + (end_received_bytes - start_received_bytes).ToString() + Environment.NewLine;
                txtboxInfo.Text += Environment.NewLine + "Sent Start (in MB): " + start_sent_bytes.ToString() + Environment.NewLine;
                txtboxInfo.Text += "  Sent End (in MB): " + end_sent_bytes.ToString() + Environment.NewLine;                
                txtboxInfo.Text += "Sent Total (in MB): " + (end_sent_bytes - start_sent_bytes).ToString() + Environment.NewLine;

                writetoFile();

                lblTime.Text = "";
            }
            catch (Exception ex)
            {
                txtboxInfo.Text = "Error !" + Environment.NewLine + ex.Message.ToString();
                _timer.Stop();
                lblTime.Text = "";                
                btnCancel.Enabled = false;
                btnMonitor.Enabled = false;
                btnCancel.Text = "";
                btnMonitor.Text = "";
                btnMonitor.BackColor = Color.Transparent;
                btnMonitor.FlatAppearance.BorderSize = 0;
            }
        }

        protected void writetoFile()
        {
            string path_file = @"C:\\Documents and Settings\\user\\Desktop\\Test Tracer.txt";
            string empty_line = "===============================================================";
            if (System.IO.File.Exists(path_file))
            {
                System.IO.File.AppendAllText(path_file, empty_line + Environment.NewLine + "Connection opened: " + _startTime + Environment.NewLine + "Connection Closed: " + DateTime.Now.ToString() + Environment.NewLine + Environment.NewLine + txtboxInfo.Text + Environment.NewLine);
            }
        }

        protected void timerTicker(object sender, EventArgs e)
        {
            var timeSinceStartTime = DateTime.Now - _startTime;
            timeSinceStartTime = new TimeSpan(timeSinceStartTime.Hours,
                                              timeSinceStartTime.Minutes,
                                              timeSinceStartTime.Seconds);                        
            lblTime.Text = "Time: " + timeSinceStartTime.ToString();

            if (adapter.OperationalStatus.ToString().ToUpper() != "UP")
            {
                MessageBox.Show("Connection Lost!");
                closeEverything(this, e);
            }
        }
    }
}


这篇关于仅当我连接到互联网时才能启动Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆