在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C# win8系统 adsl拨号换IP 源码下载

C# win8系统 adsl拨号换IP 源码下载

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:3.09M
  • 下载次数:20
  • 浏览次数:620
  • 发布时间:2016-03-22
  • 实例类别:C#语言基础
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: adsl拨号 IP C# adsl 拨号

实例介绍

【实例简介】

【实例截图】

【核心代码】

   public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        RasConnectionWatcher watcher;
        Thread oThread;
        private volatile bool _shouldStop;
        int[] isPPPOE;
        private void Form1_Load(object sender, EventArgs e)
        {
            //declarations
            RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\RAS AutoDial\\Default\\", true);
            watcher = new RasConnectionWatcher();
            Form1.CheckForIllegalCrossThreadCalls = false;

            //load config file
            PersistentSettings.Instance.Load("win8redialer.config");
            chkAutoStart.Checked = bool.Parse(PersistentSettings.Instance.GetValue("AutoStart", "false"));
            chkAutoDial.Checked = bool.Parse(PersistentSettings.Instance.GetValue("AutoDial", "false"));
            chkNoBytes.Checked = bool.Parse(PersistentSettings.Instance.GetValue("NoBytes", "false"));
            chkHosted.Checked = bool.Parse(PersistentSettings.Instance.GetValue("RestartHostedNetwork", "false"));

            txtUserName.Text = PersistentSettings.Instance.GetValue("Username","" );
            txtPassword.Text = PersistentSettings.Instance.GetValue("Password", "");

            // get list of connections
            try
            {
                RasPhoneBook pbk = new RasPhoneBook();
                pbk.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
                isPPPOE = new int[pbk.Entries.Count];
                int i=0;
                foreach (RasEntry entry in pbk.Entries)
                {
                    if (entry.DialMode == DotRas.RasDialMode.None)
                        isPPPOE[i] = 1;
                    else
                        isPPPOE[i] = 0;

                    i  ;
                    listBox1.Items.Add(entry.Name);
                }
            }
            catch (Exception er)
            {
                appendLog(er.Message);
            }

            //detect default connection
            try
            {
                for (int i = 0; i < listBox1.Items.Count; i  )
                {
                    if (rkApp != null)
                    {
                        if (listBox1.Items[i].ToString() == rkApp.GetValue("DefaultInternet").ToString())
                        {
                            listBox1.SelectedIndex = i;
                            break;
                        }
                    }
                    else
                    {
                        appendLog("Unable to detect Default connection.");
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                appendLog(ex.Message);
            }
            //Auto dial
            if (chkAutoDial.Checked == true)
            {
                button1_Click(sender, e);
            }
        }
        public void checkUpdate()
        {
            VersionHelper versionHelper = new VersionHelper();
            if (versionHelper.CheckForNewVersion())
            {
                if (MessageBox.Show("New Version of Windows 8 Redialer is Available. Download?", "Update", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    versionHelper.DownloadNewVersion();
            }
        }
        public void appendLog(string str)
        {
            if (txtStatus.Text =="")
                txtStatus.AppendText("["   DateTime.Now.ToString()   "]:"   str);
            else
                txtStatus.AppendText(Environment.NewLine   "["   DateTime.Now.ToString()   "]:"   str);

            using (StreamWriter sw = File.AppendText("log.txt"))
            {
                sw.WriteLine("["   DateTime.Now.ToString()   "]:"   str);
            }
        }
        public void button1_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex == -1)
            {
                appendLog("Select a connection...");
            }
            else
            {
                try
                {
                    appendLog("Win8 Redialer Started...");
                    button1.Enabled = false;
                    button2.Enabled = true;

                    Begin();

                    RasConnection r = RasConnection.GetActiveConnectionByName(listBox1.Items[listBox1.SelectedIndex].ToString(), RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
                    if (r == null)
                    {
                        _shouldStop = false;
                        oThread = new Thread(new ThreadStart(connect));
                        oThread.Start();

                    }
                }
                catch (Exception er)
                {
                    appendLog(er.Message);
                }
            }
        }

        public void Begin()
        {
            try
            {
                if (chkNoBytes.Checked)
                    timer2.Enabled = true;

                watcher.Connected  = new EventHandler<RasConnectionEventArgs>(this.watcher_Connected);
                watcher.Disconnected  = new EventHandler<RasConnectionEventArgs>(this.watcher_Disconnected);
                watcher.EnableRaisingEvents = true;
            }
            catch (Exception er)
            {
                appendLog(er.Message);
            }
        }
        public void Stop()
        {
            try
            {
                watcher.EnableRaisingEvents = false;
                timer2.Enabled = false;
                RequestStop();
            }
            catch (Exception er)
            {
                appendLog(er.Message);
            }
        }
        private void watcher_Connected(object sender, RasConnectionEventArgs e)
        {
            // A connection has successfully connected.

        }
        public void connect()
        {

        retry:

            try
            {
                if (!_shouldStop)
                {
                    using (RasDialer dialer = new RasDialer())
                    {
                        appendLog("Connecting...");

                        dialer.EntryName = listBox1.Items[listBox1.SelectedIndex].ToString();
                        dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);

                        if (isPPPOE[listBox1.SelectedIndex] == 1)
                            dialer.Credentials = new System.Net.NetworkCredential(txtUserName.Text, txtPassword.Text);

                        dialer.Dial();
                        appendLog("Connected...");

                        if (chkHosted.Checked)
                            RunCmdFile();
                    }
                }
            }
            catch (Exception er)
            {
                appendLog(er.Message);
                appendLog("Trying in 10 secs...");
                Thread.Sleep(1000 * 10);
                goto retry;
            }
        }
        public void RequestStop()
        {
            _shouldStop = true;
        }
        private void RunCmdFile()
        {
            //run command file to reinstall app.
            var p = new Process();
            p.StartInfo = new ProcessStartInfo("cmd.exe", "/c hosted.cmd");
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            //p.WaitForExit();
        }
        private void watcher_Disconnected(object sender, RasConnectionEventArgs e)
        {
            appendLog("Disconnected...");
            _shouldStop = false;
            oThread = new Thread(new ThreadStart(connect));
            oThread.Start();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (listBox1.SelectedIndex != -1)
                {
                    RasConnection r = RasConnection.GetActiveConnectionByName(listBox1.Items[listBox1.SelectedIndex].ToString(), RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
                    if (r == null)
                        appendLog("Current Status:Disconnected");
                    else
                        appendLog("Current Status:"   r.GetConnectionStatus().ConnectionState);

                    if (button1.Enabled == false)
                        button1.Enabled = true;
                }
            }
            catch (Exception er)
            {
                appendLog(er.Message);
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            appendLog("Win8 Redialer Stopped...");
            button1.Enabled = true;
            button2.Enabled = false;
            Stop();
        }

        private void Form1_Resize(object sender, EventArgs e)
        {

            if (FormWindowState.Minimized == this.WindowState)
            {
                notifyIcon1.Visible = true;
                notifyIcon1.ShowBalloonTip(500);
                this.Hide();
            }
            else if (FormWindowState.Normal == this.WindowState)
            {
                notifyIcon1.Visible = false;
            }

        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (chkNoBytes.Checked == true)
            {
                RasConnection r = RasConnection.GetActiveConnectionByName(listBox1.Items[listBox1.SelectedIndex].ToString(), RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
                if (r != null)
                {
                    using (TcpClient tcp = new TcpClient())
                    {
                        IAsyncResult ar = tcp.BeginConnect("google.com", 80, null, null);
                        System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                        try
                        {
                            if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                            {
                                tcp.Close();
                                appendLog("No Bytes. Disconnecting...");
                                r.HangUp();
                            }

                            //tcp.EndConnect(ar);
                        }
                        finally
                        {
                            wh.Close();
                        }
                    }
                }
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Created By: Ankit Sharma"   Environment.NewLine   "Download available at: http://www.ankitsharma.info"   Environment.NewLine   "For your suggestions & bug reports email at ankit@ankitsharma.info", "About Win8 Redialer", MessageBoxButtons.OK);
            About about = new About();
            about.ShowDialog();
        }

        private void txtStatus_TextChanged(object sender, EventArgs e)
        {
            //File.WriteAllText("log.txt", txtStatus.Text);
        }

        private void chkAutoStart_CheckedChanged(object sender, EventArgs e)
        {
            RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (chkAutoStart.Checked == true)
                rkApp.SetValue("Win8 Redialer", Application.ExecutablePath.ToString());
            else
                rkApp.DeleteValue("Win8 Redialer", false);

            PersistentSettings.Instance.SetValue("AutoStart", chkAutoStart.Checked.ToString());
            PersistentSettings.Instance.Save();
        }

        private void chkAutoDial_CheckedChanged(object sender, EventArgs e)
        {
            PersistentSettings.Instance.SetValue("AutoDial", chkAutoDial.Checked.ToString());
            PersistentSettings.Instance.Save();
        }

        private void chkNoBytes_CheckedChanged(object sender, EventArgs e)
        {
            PersistentSettings.Instance.SetValue("NoBytes", chkNoBytes.Checked.ToString());
            PersistentSettings.Instance.Save();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            PersistentSettings.Instance.SetValue("Username", txtUserName.Text);
            PersistentSettings.Instance.SetValue("Password", txtPassword.Text);
            PersistentSettings.Instance.Save();
            MessageBox.Show("Saved!");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            checkUpdate();
            timer1.Enabled = false;
        }

        private void chkHosted_CheckedChanged(object sender, EventArgs e)
        {
            PersistentSettings.Instance.SetValue("RestartHostedNetwork", chkHosted.Checked.ToString());
            PersistentSettings.Instance.Save();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            var result = MessageBox.Show("Are you sure you want to exit the application?", "Exit Win8 Redialer?",
                             MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question);

            e.Cancel = (result == DialogResult.No);
        }

    }

标签: adsl拨号 IP C# adsl 拨号

实例下载地址

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警