using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace NetworkSpeedTest { public partial class MainForm : Form { private DataTable adapterTable; private PerformanceCounter netCounter; private Timer timer; private string networkCard; private int maxSpeed = 0; public MainForm() { InitializeComponent(); InitInstance(); } public void InitInstance() { NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); adapterTable = new DataTable(); adapterTable.Columns.Add("Name", typeof(string)); adapterTable.Columns.Add("Description", typeof(string)); for (int i = 0; i < adapters.Length; i++) { adapterTable.Rows.Add(new string[] { adapters[i].Name, adapters[i].Description }); } CardComboBox.DataSource = adapterTable.DefaultView; CardComboBox.ValueMember = "Description"; } private void StartMeasuring() { StartButton.Text = "중지"; maxSpeed = 0; SpeedBar.Value = 0; SpeedBar.Maximum = 0; timer = new Timer(); timer.Interval = 1000; timer.Tick += new EventHandler(Timer_Tick); timer.Start(); } private void StopMeasuring() { StartButton.Text = "측정"; timer.Stop(); } private void Timer_Tick(object sender, EventArgs e) { try { int speed = (int)netCounter.NextValue(); if (speed > maxSpeed) { maxSpeed = speed; SpeedBar.Maximum = maxSpeed; MaxSpeedLabel.Text = string.Format("{0} bps", maxSpeed.ToString("N0")); } SpeedBar.Value = speed; float percentage = maxSpeed == 0f ? 0f : (float)speed / (float)maxSpeed * 100f; SpeedLabel.Text = string.Format("{0} bps ({1}%)", speed.ToString("N0"), percentage.ToString("N2")); } catch (Exception ex) { StopMeasuring(); MessageBox.Show("다음과 같은 이유로 측정할 수 없습니다." + Environment.NewLine + ex.Message); } } private void StartButton_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(networkCard)) { MessageBox.Show("네트워크 카드를 선택해 주십시오."); } if (StartButton.Text == "측정") { StartMeasuring(); } else { StopMeasuring(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } private void CardComboBox_SelectedIndexChanged(object sender, EventArgs e) { try { DataRowView rowView = CardComboBox.SelectedItem as DataRowView; if (rowView == null) return; string description = rowView.Row["Description"].ToString(); networkCard = description .Replace('(', '[') .Replace(')', ']') .Replace('/', '_'); netCounter = new PerformanceCounter(); netCounter.CategoryName = "Network Interface"; netCounter.CounterName = "Bytes Total/sec"; netCounter.InstanceName = networkCard; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } }