• C# 常用功能整合-3


    目录

    WebSocket

    HTTP通讯

    Task常用的两种使用方式

    定时器

    比较两个对象的属性值是否相等

    设置软件开机启动


    WebSocket

    一、需求

    在使用之前,引入Fleck插件,下面案例将采用winfrom作为服务器,html为客户端

    需要注意的是,本案例经过测试有一个问题,就是客户端如果连接上服务器后,如果长时间不通讯,那么连接会自动断开,这里其实可以写一个类似TCP协议的心跳机制来解决这个问题。

    二、WebSocket 封装

     web_socket代码

    1. using Fleck;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using System.Text;
    6. using System.Threading.Tasks;
    7. namespace WebSocket
    8. {
    9. public class Web_Socket
    10. {
    11. //客户端url以及其对应的Socket对象字典
    12. IDictionary<string, IWebSocketConnection> dic_Sockets = new Dictionary<string, IWebSocketConnection>();
    13. //创建一个 websocket ,0.0.0.0 为监听所有的的地址
    14. WebSocketServer server = new WebSocketServer("ws://0.0.0.0:30000");
    15. //打开连接委托
    16. public delegate void _OnOpen(string ip);
    17. public event _OnOpen OnOpen;
    18. //关闭连接委托
    19. public delegate void _OnClose(string ip);
    20. public event _OnClose OnClose;
    21. //当收到消息
    22. public delegate void _OnMessage(string ip, string msg);
    23. public event _OnMessage OnMessage;
    24. ///
    25. /// 初始化
    26. ///
    27. private void Init()
    28. {
    29. //出错后进行重启
    30. server.RestartAfterListenError = true;
    31. //开始监听
    32. server.Start(socket =>
    33. {
    34. //连接建立事件
    35. socket.OnOpen = () =>
    36. {
    37. //获取客户端网页的url
    38. string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
    39. dic_Sockets.Add(clientUrl, socket);
    40. if (OnOpen != null) OnOpen(clientUrl);
    41. Console.WriteLine(DateTime.Now.ToString() + " | 服务器:和客户端网页:" + clientUrl + " 建立WebSock连接!");
    42. };
    43. //连接关闭事件
    44. socket.OnClose = () =>
    45. {
    46. string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
    47. //如果存在这个客户端,那么对这个socket进行移除
    48. if (dic_Sockets.ContainsKey(clientUrl))
    49. {
    50. dic_Sockets.Remove(clientUrl);
    51. if (OnClose != null) OnClose(clientUrl);
    52. }
    53. Console.WriteLine(DateTime.Now.ToString() + " | 服务器:和客户端网页:" + clientUrl + " 断开WebSock连接!");
    54. };
    55. //接受客户端网页消息事件
    56. socket.OnMessage = message =>
    57. {
    58. string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
    59. Receive(clientUrl, message);
    60. if (OnMessage != null) OnMessage(clientUrl, message);
    61. };
    62. });
    63. }
    64. ///
    65. /// 向客户端发送消息
    66. ///
    67. /// 客户端实例
    68. /// 消息内容
    69. public void Send(string clientUrl, string message)
    70. {
    71. IWebSocketConnection webSocketConnection = GetUserSocketInstance(clientUrl);
    72. if (webSocketConnection != null)
    73. {
    74. if (webSocketConnection.IsAvailable)
    75. {
    76. webSocketConnection.Send(message);
    77. }
    78. }
    79. }
    80. ///
    81. /// 接收消息
    82. ///
    83. ///
    84. ///
    85. private void Receive(string clientUrl, string message)
    86. {
    87. Console.WriteLine(DateTime.Now.ToString() + " | 服务器:【收到】来客户端网页:" + clientUrl + "的信息:\n" + message);
    88. }
    89. ///
    90. /// 获取用户实例
    91. ///
    92. /// 用户的地址
    93. public IWebSocketConnection GetUserSocketInstance(string clientUrl)
    94. {
    95. if (dic_Sockets.ContainsKey(clientUrl))
    96. return dic_Sockets[clientUrl];
    97. else
    98. return null;
    99. }
    100. ///
    101. /// 关闭某一个用户的连接
    102. ///
    103. ///
    104. public void CloseUserConnect(string clientUrl)
    105. {
    106. IWebSocketConnection webSocketConnection = GetUserSocketInstance(clientUrl);
    107. if (webSocketConnection != null)
    108. webSocketConnection.Close();
    109. }
    110. ///
    111. /// 关闭与客户端的所有的连接
    112. ///
    113. public void CloseAllConnect()
    114. {
    115. foreach (var item in dic_Sockets.Values)
    116. {
    117. if (item != null)
    118. {
    119. item.Close();
    120. }
    121. }
    122. }
    123. public Web_Socket()
    124. {
    125. Init();
    126. }
    127. }
    128. }

    三、前端部分

    winform 界面

    Form1代码:

    1. using Fleck;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.ComponentModel;
    5. using System.Data;
    6. using System.Drawing;
    7. using System.IO;
    8. using System.Linq;
    9. using System.Text;
    10. using System.Threading.Tasks;
    11. using System.Windows.Forms;
    12. namespace WebSocket
    13. {
    14. public partial class Form1 : Form
    15. {
    16. public Form1()
    17. {
    18. InitializeComponent();
    19. }
    20. private Web_Socket webSocket = new Web_Socket();
    21. private void Form1_Load(object sender, EventArgs e)
    22. {
    23. webSocket.OnOpen += this.OnOpen;
    24. webSocket.OnClose += this.OnClose;
    25. webSocket.OnMessage += this.OnMessage;
    26. Init();
    27. }
    28. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    29. {
    30. webSocket.CloseAllConnect();
    31. }
    32. private void Init()
    33. {
    34. }
    35. //当有客户端连接
    36. private void OnOpen(string clientUrl)
    37. {
    38. this.Invoke(new MethodInvoker(delegate
    39. {
    40. ComboBox_IPAddres.Items.Add(clientUrl);
    41. if (ComboBox_IPAddres.Items.Count > 0)
    42. ComboBox_IPAddres.SelectedIndex = 0;
    43. ListBox_IPList.Items.Insert(ListBox_IPList.Items.Count, clientUrl);
    44. }));
    45. AddLogToListView("用户加入", string.Empty, string.Format("IP:{0} 加入了连接", clientUrl), true);
    46. }
    47. //当客户端关闭
    48. private void OnClose(string clientUrl)
    49. {
    50. this.Invoke(new MethodInvoker(delegate
    51. {
    52. ComboBox_IPAddres.Items.Remove(clientUrl);
    53. ListBox_IPList.Items.Remove(clientUrl);
    54. }));
    55. AddLogToListView("用户退出", string.Empty, string.Format("IP:{0} 关闭了连接", clientUrl), true);
    56. }
    57. //当收到客户端消息
    58. private void OnMessage(string clientUrl, string message)
    59. {
    60. AddLogToListView("服务器接收", clientUrl, message);
    61. }
    62. ///
    63. /// 添加日志到日志列表
    64. ///
    65. ///
    66. ///
    67. private void AddLogToListView(string title, string clientUrl, string message, bool rest = false)
    68. {
    69. this.Invoke(new MethodInvoker(delegate
    70. {
    71. int len = ListBox_MessageList.Items.Count;
    72. if (!rest)
    73. ListBox_MessageList.Items.Insert(len, string.Format("[{0}] IP:{1} 内容:{2}", title, clientUrl, message));
    74. else
    75. ListBox_MessageList.Items.Insert(len, string.Format("[{0}] {1}", title, message));
    76. }));
    77. }
    78. ///
    79. /// 发送按钮点击事件
    80. ///
    81. ///
    82. ///
    83. private void Button_Send_Click(object sender, EventArgs e)
    84. {
    85. string clientUrl = ComboBox_IPAddres.Text;
    86. string content = TextBox_Message.Text;
    87. if (string.IsNullOrEmpty(content))
    88. {
    89. MessageBox.Show("发送内容为空");
    90. return;
    91. }
    92. if (string.IsNullOrEmpty(clientUrl))
    93. {
    94. MessageBox.Show("请选择一个IP地址");
    95. return;
    96. }
    97. webSocket.Send(clientUrl, content);
    98. TextBox_Message.Text = string.Empty;
    99. AddLogToListView("服务器发送", clientUrl, content);
    100. }
    101. }
    102. }

    四、网页端

    html:

    1. HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    2. <html>
    3. <head>
    4. <title>websocket clienttitle>
    5. <script type="text/javascript">
    6. var start = function () {
    7. var inc = document.getElementById('incomming');
    8. var wsImpl = window.WebSocket || window.MozWebSocket;
    9. var form = document.getElementById('sendForm');
    10. var input = document.getElementById('sendText');
    11. inc.innerHTML += "连接服务器..
      "
      ;
    12. // 创建一个新的websocket并连接
    13. window.ws = new wsImpl('ws://localhost:30000/');
    14. // 当数据来自服务器时,将调用此方法
    15. ws.onmessage = function (evt) {
    16. inc.innerHTML += ("[来自服务器的消息] " + evt.data + '
      '
      );
    17. console.log("[来自服务器的消息] " + evt.data);
    18. };
    19. // 当建立连接时,将调用此方法
    20. ws.onopen = function () {
    21. inc.innerHTML += '已建立连接..
      '
      ;
    22. };
    23. // 当连接关闭时,将调用此方法
    24. ws.onclose = function () {
    25. inc.innerHTML += '连接已关闭..
      '
      ;
    26. }
    27. form.addEventListener('submit', function (e) {
    28. e.preventDefault();
    29. var val = input.value;
    30. ws.send(val);
    31. input.value = "";
    32. });
    33. }
    34. window.onload = start;
    35. script>
    36. head>
    37. <body>
    38. <form id="sendForm">
    39. <span>输入内容按回车发送消息span> <br/>
    40. <input id="sendText" placeholder="Text to send" />
    41. form>
    42. <pre id="incomming">pre>
    43. body>
    44. html>

    经过测试,发送,接收消息正常

    HTTP通讯

    代码:

    1. using Newtonsoft.Json;
    2. using System.IO;
    3. using System.Net;
    4. using System.Text;
    5. namespace HTTP
    6. {
    7. public class RestClient
    8. {
    9. ///
    10. /// Get请求
    11. ///
    12. /// 请求url
    13. ///
    14. public static string Get(string url)
    15. {
    16. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    17. if (req == null || req.GetResponse() == null)
    18. return string.Empty;
    19. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    20. if (resp == null)
    21. return string.Empty;
    22. using (Stream stream = resp.GetResponseStream())
    23. {
    24. //获取内容
    25. using (StreamReader reader = new StreamReader(stream))
    26. {
    27. return reader.ReadToEnd();
    28. }
    29. }
    30. }
    31. ///
    32. /// Post请求
    33. ///
    34. ///
    35. ///
    36. ///
    37. public static string Post(string url, object postData)
    38. {
    39. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    40. if (req == null)
    41. return string.Empty;
    42. req.Method = "POST";
    43. req.ContentType = "application/json";
    44. req.Timeout = 15000;
    45. byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postData));
    46. //注意:无需手动指定长度 (否则可能会报流未处理完就关闭的异常,因为ContentLength时候会比真实post数据长度大)
    47. //req.ContentLength = data.Length;
    48. using (Stream reqStream = req.GetRequestStream())
    49. {
    50. reqStream.Write(data, 0, data.Length);
    51. }
    52. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    53. if (resp == null)
    54. return string.Empty;
    55. using (Stream stream = resp.GetResponseStream())
    56. {
    57. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
    58. {
    59. return reader.ReadToEnd();
    60. }
    61. }
    62. }
    63. }
    64. }

    上面的Post请求在有些接口可能没有效果,可以使用下面的方法,其中第一个方法是无参数的Post请求,第二个方法只要将所需的Key和Value添加进字典就行了

    1. ///
    2. /// 指定Post地址使用Get 方式获取全部字符串
    3. ///
    4. /// 请求后台地址
    5. ///
    6. public static string Post(string url)
    7. {
    8. string result = "";
    9. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    10. req.Method = "POST";
    11. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    12. Stream stream = resp.GetResponseStream();
    13. //获取内容
    14. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
    15. {
    16. result = reader.ReadToEnd();
    17. }
    18. return result;
    19. }
    20. ///
    21. /// 指定Post地址使用Get 方式获取全部字符串
    22. ///
    23. /// 请求后台地址
    24. ///
    25. public static string Post(string url, Dictionary<string, string> dic)
    26. {
    27. string result = "";
    28. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    29. req.Method = "POST";
    30. req.ContentType = "application/x-www-form-urlencoded";
    31. #region 添加Post 参数
    32. StringBuilder builder = new StringBuilder();
    33. int i = 0;
    34. foreach (var item in dic)
    35. {
    36. if (i > 0)
    37. builder.Append("&");
    38. builder.AppendFormat("{0}={1}", item.Key, item.Value);
    39. i++;
    40. }
    41. byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
    42. req.ContentLength = data.Length;
    43. using (Stream reqStream = req.GetRequestStream())
    44. {
    45. reqStream.Write(data, 0, data.Length);
    46. reqStream.Close();
    47. }
    48. #endregion
    49. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    50. Stream stream = resp.GetResponseStream();
    51. //获取响应内容
    52. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
    53. {
    54. result = reader.ReadToEnd();
    55. }
    56. return result;
    57. }

    Task常用的两种使用方式

    1.无返回值方式

    代码:

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Threading;
    6. using System.Threading.Tasks;
    7. namespace MyTask
    8. {
    9. class Program
    10. {
    11. static void Main(string[] args)
    12. {
    13. List taskList = new List();
    14. taskList.Add(Task.Factory.StartNew(() =>
    15. {
    16. Thread.Sleep(1000);
    17. Console.WriteLine("1秒执行结束");
    18. }));
    19. taskList.Add(Task.Factory.StartNew(() =>
    20. {
    21. Thread.Sleep(800);
    22. Console.WriteLine("o.8秒执行结束");
    23. }));
    24. Console.WriteLine("执行中");
    25. TaskFactory taskFactory = new TaskFactory();
    26. taskList.Add(taskFactory.ContinueWhenAll(taskList.ToArray(), tArray =>
    27. {
    28. Thread.Sleep(200);
    29. Console.WriteLine("等待这些完成后执行");
    30. }));
    31. Console.ReadKey();
    32. }
    33. }
    34. }

    运行:

    这里由于作了延时处理,执行顺序不一致

    假设任务中出现异常:

    代码:

    1. taskList.Add(Task.Factory.StartNew(() =>
    2. {
    3. try
    4. {
    5. int a = int.Parse("");
    6. }
    7. catch (Exception ex)
    8. {
    9. Console.WriteLine("=========异常:" + ex.Message);
    10. }
    11. Console.WriteLine("=========第二种方式");
    12. }));

    运行:

    2.有返回值方式

    代码:

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Threading;
    6. using System.Threading.Tasks;
    7. namespace MyTask
    8. {
    9. class Program
    10. {
    11. static void Main(string[] args)
    12. {
    13. Listint>> taskList1 = new Listint>>();
    14. taskList1.Add(Task<int>.Factory.StartNew(() =>
    15. {
    16. int num = 3 * 5;
    17. Console.WriteLine("有返回值的任务队列 1");
    18. return num;
    19. }
    20. ));
    21. taskList1.Add(Task<int>.Factory.StartNew(() =>
    22. {
    23. int num = 3 * 7;
    24. Console.WriteLine("有返回值的任务队列 2");
    25. return num;
    26. }
    27. ));
    28. new TaskFactory().ContinueWhenAll(taskList1.ToArray(), tArray =>
    29. {
    30. Console.WriteLine("有返回值的任务队列执行完毕");
    31. foreach (Task<int> item in taskList1)
    32. {
    33. Console.WriteLine("执行结果:" + item.Result);
    34. }
    35. });
    36. Console.ReadKey();
    37. }
    38. }
    39. }

    运行:

    定时器

    第一种:用线程

    1. private void Form1_Load(object sender, EventArgs e){
    2. timer = new System.Timers.Timer();
    3. timer.Interval = 3000;
    4. timer.AutoReset = false;
    5. timer.Enabled = true;
    6. timer.Elapsed += new System.Timers.ElapsedEventHandler(GetCurDateTime);
    7. }
    8. private void GetCurDateTime(object sender, System.Timers.ElapsedEventArgs e)
    9. {
    10. Label_Log.Text = string.Empty;
    11. }

    第二种:用winform 自带的组件

    1. private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
    2. private void Form1_Load(object sender, EventArgs e){
    3. timer.Interval = 3000;
    4. timer.Tick += GetCurDateTime;
    5. timer.Enabled = true;
    6. }
    7. private void GetCurDateTime(object sender, EventArgs e)
    8. {
    9. Label_Log.Text = string.Empty;
    10. }

    比较两个对象的属性值是否相等

    需要注意的是,两个对象中的字段必须是属性,带有get,set,否则无法识别,返回的就是false

    代码

    1. ///
    2. /// 比较--两个类型一样的实体类对象的值
    3. ///
    4. ///
    5. /// 返回true表示两个对象的数据相同,返回false表示不相同
    6. private bool CompareType<T>(T oneT, T twoT)
    7. {
    8. bool result = true;//两个类型作比较时使用,如果有不一样的就false
    9. Type typeOne = oneT.GetType();
    10. Type typeTwo = twoT.GetType();
    11. //如果两个T类型不一样 就不作比较
    12. if (!typeOne.Equals(typeTwo)) { return false; }
    13. PropertyInfo[] pisOne = typeOne.GetProperties(); //获取所有公共属性(Public)
    14. PropertyInfo[] pisTwo = typeTwo.GetProperties();
    15. //如果长度为0返回false
    16. if (pisOne.Length <= 0 || pisTwo.Length <= 0)
    17. {
    18. return false;
    19. }
    20. //如果长度不一样,返回false
    21. if (!(pisOne.Length.Equals(pisTwo.Length))) { return false; }
    22. //遍历两个T类型,遍历属性,并作比较
    23. for (int i = 0; i < pisOne.Length; i++)
    24. {
    25. //获取属性名
    26. string oneName = pisOne[i].Name;
    27. string twoName = pisTwo[i].Name;
    28. //获取属性的值
    29. object oneValue = pisOne[i].GetValue(oneT, null);
    30. object twoValue = pisTwo[i].GetValue(twoT, null);
    31. //比较,只比较值类型
    32. if ((pisOne[i].PropertyType.IsValueType || pisOne[i].PropertyType.Name.StartsWith("String")) && (pisTwo[i].PropertyType.IsValueType || pisTwo[i].PropertyType.Name.StartsWith("String")))
    33. {
    34. if (oneName.Equals(twoName))
    35. {
    36. if (oneValue == null)
    37. {
    38. if (twoValue != null)
    39. {
    40. result = false;
    41. break; //如果有不一样的就退出循环
    42. }
    43. }
    44. else if (oneValue != null)
    45. {
    46. if (twoValue != null)
    47. {
    48. if (!oneValue.Equals(twoValue))
    49. {
    50. result = false;
    51. break; //如果有不一样的就退出循环
    52. }
    53. }
    54. else if (twoValue == null)
    55. {
    56. result = false;
    57. break; //如果有不一样的就退出循环
    58. }
    59. }
    60. }
    61. else
    62. {
    63. result = false;
    64. break;
    65. }
    66. }
    67. else
    68. {
    69. //如果对象中的属性是实体类对象,递归遍历比较
    70. bool b = CompareType(oneValue, twoValue);
    71. if (!b) { result = b; break; }
    72. }
    73. }
    74. return result;
    75. }
    76. //调用
    77. private void btnOrder_Click(object sender, EventArgs e)
    78. {
    79. //实体类比较
    80. UserVo userVoOne = new UserVo();
    81. UserVo userVoTwo = new UserVo();
    82. userVoOne.UserID = 1;
    83. //userVoOne.UserAccount = "a";
    84. userVoTwo.UserID = 1;
    85. bool flag = CompareType(userVoOne, userVoTwo);
    86. if (flag)
    87. {
    88. MessageBox.Show("两个类数据相同");
    89. }
    90. else
    91. {
    92. MessageBox.Show("两个类数据不相同");
    93. }
    94. }

    设置软件开机启动

    界面:

    代码:

    1. using Microsoft.Win32;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.ComponentModel;
    5. using System.Data;
    6. using System.Drawing;
    7. using System.IO;
    8. using System.Linq;
    9. using System.Text;
    10. using System.Threading.Tasks;
    11. using System.Windows.Forms;
    12. namespace 开机启动
    13. {
    14. public partial class Form1 : Form
    15. {
    16. public Form1()
    17. {
    18. InitializeComponent();
    19. }
    20. //获得应用程序路径
    21. private string StrAssName = string.Empty;
    22. //获得应用程序名
    23. private string ShortFileName = string.Empty;
    24. private void Form1_Load(object sender, EventArgs e)
    25. {
    26. }
    27. //添加到开机启动
    28. public void AddPowerBoot()
    29. {
    30. try
    31. {
    32. if(string.IsNullOrEmpty(ShortFileName) || string.IsNullOrEmpty(StrAssName))
    33. {
    34. MessageBox.Show("输入框不能为空");
    35. return;
    36. }
    37. //此方法把启动项加载到注册表中
    38. //获得应用程序路径
    39. //string StrAssName = Application.StartupPath + @"\" + Application.ProductName + @".exe";
    40. //获得应用程序名
    41. //string ShortFileName = Application.ProductName;
    42. //路径:HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run
    43. RegistryKey rgkRun = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    44. if (rgkRun == null)
    45. {
    46. rgkRun = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
    47. }
    48. rgkRun.SetValue(ShortFileName, StrAssName);
    49. MessageBox.Show("添加到注册表成功");
    50. }
    51. catch (Exception ex)
    52. {
    53. MessageBox.Show("执行错误:" + ex.Message);
    54. }
    55. }
    56. //移除开机启动
    57. public void RemovePowerBoot()
    58. {
    59. try
    60. {
    61. if (string.IsNullOrEmpty(ShortFileName) || string.IsNullOrEmpty(StrAssName))
    62. {
    63. MessageBox.Show("输入框不能为空");
    64. return;
    65. }
    66. //此删除注册表中启动项
    67. //获得应用程序名
    68. //string ShortFileName = Application.ProductName;
    69. RegistryKey rgkRun = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    70. if (rgkRun == null)
    71. {
    72. rgkRun = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
    73. }
    74. rgkRun.DeleteValue(ShortFileName, false);
    75. MessageBox.Show("移除注册表成功");
    76. }
    77. catch (Exception ex)
    78. {
    79. MessageBox.Show("执行错误:" + ex.Message);
    80. }
    81. }
    82. //设置开机启动
    83. private void Button_SetPowerBoot_Click(object sender, EventArgs e)
    84. {
    85. AddPowerBoot();
    86. }
    87. //移除开机启动
    88. private void Button_RemovePowerBoot_Click(object sender, EventArgs e)
    89. {
    90. RemovePowerBoot();
    91. }
    92. //选择要操作的程序
    93. private void Button_GetModuleFileName_Click(object sender, EventArgs e)
    94. {
    95. //创建对象
    96. OpenFileDialog ofg = new OpenFileDialog();
    97. //设置默认打开路径(绝对路径)
    98. ofg.InitialDirectory = "C:\\Users\\Administrator\\Desktop";
    99. //设置打开标题、后缀
    100. ofg.Title = "请选择程序的exe文件";
    101. ofg.Filter = "exe文件|*.exe";
    102. string path = string.Empty;
    103. if (ofg.ShowDialog() == DialogResult.OK)
    104. {
    105. //得到打开的文件路径(包括文件名)
    106. path = ofg.FileName.ToString();
    107. Console.WriteLine("打开文件路径是:" + path);
    108. TextBox_GetModuleFileName.Text = path;
    109. StrAssName = path;
    110. string[] arr = path.Split('\\');
    111. ShortFileName = arr[arr.Length - 1];
    112. Label_ProgramName.Text = "应用程序名:" + ShortFileName;
    113. }
    114. else if (ofg.ShowDialog() == DialogResult.Cancel)
    115. {
    116. MessageBox.Show("未选择打开文件!");
    117. }
    118. }
    119. }
    120. }

    程序一定要用管理员身份运行,否则会报错

    end

  • 相关阅读:
    vscode 画流程图
    我的北航MEM之路 & MEM备考经验分享
    神经网络中正则化和正则化率的含义
    ElfBoard,为嵌入式学习爱好者创造更具价值的学习体验
    C语言之文件操作
    使用匿名函数在Golang中的好处
    设计模式之责任链模式
    kubernetes(K8S)笔记
    计算两个日期时间相差的天数或者时间
    基于鸽群算法优化最小二乘支持向量机lssvm实现预测附matlab代码
  • 原文地址:https://blog.csdn.net/qq_38693757/article/details/125997421