自动拨号的服务 不断修改完善中......


自动拨号.cs:

using System;
//using System.Collections.Generic;
//using System.ComponentModel;
//using System.Data;
//using System.Diagnostics;
//using System.Linq;
using System.ServiceProcess;
//using System.Text;
//using System.Windows.Forms;
using Microsoft.Win32;
using System.Net.NetworkInformation;
using System.Timers;

namespace 自动拨号
{
    public partial class 自动拨号 : ServiceBase
    {

        
        public 自动拨号()
        {
            InitializeComponent();
        }
        
        System.Timers.Timer timer1 = new System.Timers.Timer();
        
        //System.Timers.Timer timer2 = new System.Timers.Timer();
        protected override void OnStart(string[] args)
        {
            timer1.Enabled = true;
            timer1.Interval = 10000;
            //timer2.Enabled = false;
            //timer2.Interval = 10000;
            timer1.Elapsed += new ElapsedEventHandler(timer1_Tick);
            //timer2.Elapsed += new ElapsedEventHandler(timer2_Tick);

            //MessageBox.Show("自动拨号已启动");
        }


        private void timer1_Tick(object sender, EventArgs e)
        {

            //MessageBox.Show("检测Internet连接");
            //MessageBox.Show(NetOK.GetValue("NetOK").ToString());
            //textBox1.AppendText(NetOK.GetValue("NetOK").ToString() + "\r\n");
            RegistryKey NetOK = Registry.CurrentUser.CreateSubKey("NetOK");
            Ping ping = new Ping();
            PingReply pr = ping.Send("61.128.128.68");
            if (pr.Status == IPStatus.Success)//如果ping成功
            {
                //if(NetOK.GetValue("NetOK").ToString()== "no")
                    NetOK.SetValue("NetOK", "ok");

            }
            else
            {
                BoHao bohao = new BoHao();//这个以前放在函数外,现在放在函数内,内存占用已降低到9.5M但是还是在逐步增加
                NetOK.SetValue("NetOK", "no");
                //timer1.Enabled = false;
                //timer2.Enabled = true;
                bohao.StartDailer();
                //MessageBox.Show("拨号一次");

                bohao.IsConnectedToInternet();



                CreateLogFiles.wrLog("自动拨号成功! 状态码:"+bohao.Desc);
                //CreateLogFiles.Log(path,DateTime.Now.ToString("yyyy年MM月dd日hh时mm分ss秒"+"自动拨号成功"));
                //MessageBox.Show(path);
            }
        }

        /*
        private void timer2_Tick(object sender, EventArgs e)
        {
            timer2.Enabled = false;
            timer1.Enabled = true;
            
        }*/


    }
}


 ProjectInstaller.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using Microsoft.Win32;
using System.ServiceProcess;
using System.Management;



namespace 自动拨号
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }

        private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
        {
            base.OnAfterInstall(e.SavedState);

            ManagementObject wmiService = null;
            ManagementBaseObject InParam = null;
            try
            {
                wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'", "自动拨号"));
                InParam = wmiService.GetMethodParameters("Change");
                InParam["DesktopInteract"] = true;
                wmiService.InvokeMethod("Change", InParam, null);
            }
            finally
            {
                if (InParam != null)
                    InParam.Dispose();
                if (wmiService != null)
                    wmiService.Dispose();
            }


            ServiceController myService = new ServiceController("自动拨号");
            myService.Start();
            myService.Dispose();   


        }

        private void SetServiceTable(string ServiceName) 
        { 
            RegistryKey rk = Registry.LocalMachine; 
            string key = @"SYSTEM\CurrentControlSet\Services\" + ServiceName; 
            RegistryKey sub = rk.OpenSubKey(key, true); 
            int value = (int)sub.GetValue("Type"); 
            sub.SetValue("Type", value | 256);




        }

        private void SetServiceDesktopInsteract(string serviceName) 
        { 
            ManagementObject wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'", serviceName));
            ManagementBaseObject changeMethod = wmiService.GetMethodParameters("Change"); 
            changeMethod["DesktopInteract"] = true; 
            ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", changeMethod, null); 
        }
    }

}

 

 

log.cs

using System;
//using System.Diagnostics;
//using System.Text;
using System.IO;


namespace 自动拨号
{
    //<Summary>
    // This class used to created log files
    // Created by ali ahmad h - 2002
    //</Summary>
    public class CreateLogFiles
    {
        /// 



        public static void wrLog(string msg)
        {
            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase+"logs";
            if(!Directory.Exists(path))
            { Directory.CreateDirectory(path); }

            string filename = path + @"\"+DateTime.Today.ToString("yyyyMMdd") + @".log";

            string logInfo = "自动拨号服务于"+DateTime.Now.ToString("yyyy年MM月dd日hh时mm分ss秒") +msg;

     
            if (File.Exists(filename))
            {
                writeLogToFile(logInfo,filename);
            }
            else
            {
                createAndWriteLogFile(logInfo,filename);
            }
        }
 
        /// <summary>
        /// 往日志文件中追加信息
        /// </summary>
        /// <param name="logInfo"></param>
        static private void writeLogToFile(string logInfo,string logFile)
        {
            try
            {
                using (StreamWriter m_streamWriter = File.AppendText(logFile))
                {
                    m_streamWriter.Flush();
                    m_streamWriter.WriteLine(logInfo);
                    m_streamWriter.Flush();
                    m_streamWriter.Dispose();
                    m_streamWriter.Close();
                }
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.Message);
            }
        }
 
        /// <summary>
        /// 创建文件并写日志信息
        /// </summary>
        /// <param name="logInfo"></param>
        static private void createAndWriteLogFile(string logInfo,string filename)
        {
            FileStream fs = new FileStream(filename,FileMode.Create,FileAccess.Write);
            try
            {
                using (StreamWriter m_streamWriter = new StreamWriter(fs))
                {
                    m_streamWriter.Flush();
                    m_streamWriter.WriteLine(logInfo);
                    m_streamWriter.Flush();
                    m_streamWriter.Dispose();
                    m_streamWriter.Close();
                }
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.Message);
            }
            finally
            {
                fs.Dispose();
                fs.Close();
            }
        }




    }
}



 bohao.cs:

using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
//using System.Windows.Forms;

namespace 自动拨号
{
    class BoHao
    {
        private static Mutex mutex = new Mutex();
        private Process dailer = new Process();
        public int Desc;
        string EntryName = "宽带连接";
        string user = "lanxxxxxxxxxx";
        string pwd = "********";
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
        // 返回18失败,返回81成功
        public int IsConnectedToInternet()
        {
            InternetGetConnectedState(out Desc, 0);
            return Desc;
        }

        public void StartDailer()
        {
            try
            {
                if (!IsAlive("rasdial"))
                {
                    mutex.WaitOne();
                    dailer.StartInfo.FileName = "rasdial.exe";
                    dailer.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    dailer.StartInfo.Arguments = EntryName + " " + user + " " + pwd;
                    dailer.Start();
                    mutex.ReleaseMutex();
                }

            }
            catch (Exception ee)
            {
                ee.ToString();
            }
            finally
            {

            }
            dailer.Close();
        }


        private bool IsAlive(string name)
        {
            Process[] ps = Process.GetProcessesByName(name);
            if (ps.Length > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}


ProjectInstaller.Designer.cs:

namespace 自动拨号
{
    partial class ProjectInstaller
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;


        /// <summary> 
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }


        #region 组件设计器生成的代码


        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
            this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
            // 
            // serviceProcessInstaller1
            // 
            this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;//用这个被定为到“HKEY_USERS\S-1-5-19\NetOK”

            this.serviceProcessInstaller1.Password = null;
            this.serviceProcessInstaller1.Username = null;
            // 
            // serviceInstaller1
            // 
            this.serviceInstaller1.ServiceName = "自动拨号";
            this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
            this.serviceInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceInstaller1_AfterInstall);
            // 
            // ProjectInstaller
            // 
            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
            this.serviceProcessInstaller1,
            this.serviceInstaller1});


        }


        #endregion


        private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
        private System.ServiceProcess.ServiceInstaller serviceInstaller1;
    }
}




想达到的目的:

1、服务启动后,自动检测有无网络连接,没有的话就拨号。然后中途有掉线的情况,也能自动检测到并再次自动拨号......

2、希望在windows用户登录界面就能启动这个服务,以便我进入远程桌面。因为如果是直接把拨号连接放到启动项里面,在用户登录之前是不会执行的。

目前的问题:

1、内存占用过高。启动后15M左右,然后慢慢增加到70M左右,好像是系统的自动资源回收,才又回到15M,如此往返。

2、开机启动老是不成功,不知道是不是要依存与其他服务?

 

希望高手指正并完善!

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值