C#源码刷新网页 最小化托盘http get和post请求配置保存版权时间限制定时调用 单实例运行,如果已经运行则激活窗口到最前显示
生活随笔
收集整理的這篇文章主要介紹了
C#源码刷新网页 最小化托盘http get和post请求配置保存版权时间限制定时调用 单实例运行,如果已经运行则激活窗口到最前显示
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C#源碼功能示例:刷新網頁、最小化托盤、http get和post請求、配置保存、版權時間限制、定時調用、單實例運行,如果已經運行則激活窗口到最前顯示等。
單實例運行激活窗口 調用
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Threading;namespace HTMLWindowsFormsApplication3 {static class Program{/// <summary>/// 應用程序的主入口點。/// </summary>[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);SoftHelper.SoftSingle<Form1>(); //單實例運行,已運行則激活窗口// Application.Run(new Form1());//bool createdNew; //Mutex instance= new Mutex(true, "互斥名(保證在本機中唯一)", out createdNew);//if(createdNew)//{// Application.EnableVisualStyles();// Application.SetCompatibleTextRenderingDefault(false);// Application.Run(new Form1());// instance.ReleaseMutex();//}//else//{// MessageBox.Show("已經啟動了一個程序,請先退出!", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Error);// Application.Exit();//}}} }
單實例運行,如果已經運行則激活窗口到最前顯示 類
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Windows.Forms; using System.Runtime.InteropServices;namespace HTMLWindowsFormsApplication3 {public class SoftHelper{///<summary>/// 該函數設置由不同線程產生的窗口的顯示狀態/// </summary>/// <param name="hWnd">窗口句柄</param>/// <param name="cmdShow">指定窗口如何顯示。查看允許值列表,請查閱ShowWlndow函數的說明部分</param>/// <returns>如果函數原來可見,返回值為非零;如果函數原來被隱藏,返回值為零</returns>[DllImport("User32.dll")]private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);/// <summary>/// 該函數將創建指定窗口的線程設置到前臺,并且激活該窗口。鍵盤輸入轉向該窗口,并為用戶改各種可視的記號。/// 系統給創建前臺窗口的線程分配的權限稍高于其他線程。 /// </summary>/// <param name="hWnd">將被激活并被調入前臺的窗口句柄</param>/// <returns>如果窗口設入了前臺,返回值為非零;如果窗口未被設入前臺,返回值為零</returns>[DllImport("User32.dll")]private static extern bool SetForegroundWindow(IntPtr hWnd);private const int SW_SHOWNOMAL = 1;private static void HandleRunningInstance(Process instance){ShowWindowAsync(instance.MainWindowHandle, SW_SHOWNOMAL);//顯示SetForegroundWindow(instance.MainWindowHandle);//當到最前端}private static Process RuningInstance(){Process currentProcess = Process.GetCurrentProcess();Process[] Processes = Process.GetProcessesByName(currentProcess.ProcessName);foreach (Process process in Processes){if (process.Id != currentProcess.Id){return process;}}return null;}/// <summary>/// 程序以單例運行 /// </summary>public static void SoftSingle<T>() where T : Form, new(){Process process = RuningInstance();if (process == null){var mainForm = new T();Application.Run(mainForm);}else{HandleRunningInstance(process);}}} }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.Win32; using System.Net; using System.IO;namespace HTMLWindowsFormsApplication3 {public partial class Form1 : Form{System.Timers.Timer t;long num=0;Boolean textBox1HasText = false;//判斷輸入框是否有文本Boolean textBox2HasText = false;//判斷輸入框是否有文本public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){textBox1.Text= Settings1.Default.url;textBox2.Text = Settings1.Default.num;label1.Text = "自動同步" + num + "次";// button1.Focus();textBox1_Leave(null, null);textBox2_Leave(null, null);// textBox1.Text = "www.baidu.com";// webBrowser1.Navigate(textBox1.Text.ToString());SetAutoRun(Application.ExecutablePath, true);StartRefresh();// this.Hide();this.WindowState = FormWindowState.Minimized;// notifyIcon1.Visible = false;// this.ShowInTaskbar = false;// limited();}public void StartRefresh(){int time = 1;try{time = int.Parse(textBox2.Text.ToString());}catch { }t = new System.Timers.Timer(1000 * time);//實例化Timer類,設置間隔時間為10000毫秒;t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到達時間的時候執行事件;t.AutoReset = true;//設置是執行一次(false)還是一直執行(true);t.Enabled = true;//是否執行System.Timers.Timer.Elapsed事件; }private void limited(){DateTime dt1 = DateTime.Parse("2017-09-20");if (DateTime.Compare(dt1, DateTime.Now) < 0){MessageBox.Show("試用版已經到期,請聯系小黃人軟件QQ345139427");Application.Exit(); return;}}/// <summary>/// 設置應用程序開機自動運行/// </summary>/// <param name="fileName">應用程序的文件名</param> /// <param name="isAutoRun">是否自動運行,為false時,取消自動運行</param>/// <exception cref="System.Exception">設置不成功時拋出異常</exception>public static void SetAutoRun(string fileName, bool isAutoRun) //SetAutoRun(Application.ExecutablePath,true);{RegistryKey reg = null;try{if (!System.IO.File.Exists(fileName))throw new Exception("該文件不存在!");String name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);if (reg == null)reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");if (isAutoRun)reg.SetValue(name, fileName);elsereg.SetValue(name, false);}catch (Exception ex){throw new Exception(ex.ToString());}finally{if (reg != null)reg.Close();}}//textBox2獲得焦點private void textBox2_Enter(object sender, EventArgs e){if (textBox2HasText == false)textBox2.Text = "";textBox2.ForeColor = Color.Black;}//textBox2失去焦點private void textBox2_Leave(object sender, EventArgs e){if (textBox2.Text == ""){textBox2.Text = "多少秒刷新1次?";textBox2.ForeColor = Color.LightGray;textBox2HasText = false;}elsetextBox2HasText = true;}//textBox1獲得焦點private void textBox1_Enter(object sender, EventArgs e){if (textBox1HasText == false)textBox1.Text = "";textBox1.ForeColor = Color.Black;}//textBox1失去焦點private void textBox1_Leave(object sender, EventArgs e){if (textBox1.Text == ""){textBox1.Text = "需要刷新的網址";textBox1.ForeColor = Color.LightGray;textBox1HasText = false;}elsetextBox1HasText = true;}private void Form1_SizeChanged(object sender, EventArgs e){if (this.WindowState == FormWindowState.Minimized) //判斷是否最小化{this.ShowInTaskbar = false; //不顯示在系統任務欄notifyIcon1.Visible = true; //托盤圖標可見}}private void notifyIcon1_DoubleClick(object sender, EventArgs e){if (this.WindowState == FormWindowState.Minimized){this.Show();this.WindowState = FormWindowState.Normal;// notifyIcon1.Visible = false;this.ShowInTaskbar = true;}}private void checkBox1_CheckedChanged(object sender, EventArgs e){if (checkBox1.Checked) //設置{SetAutoRun(Application.ExecutablePath, true);}else{SetAutoRun(Application.ExecutablePath, false);}}private void button1_Click(object sender, EventArgs e){Settings1.Default.url = textBox1.Text.ToString();Settings1.Default.num=textBox2.Text.ToString();Settings1.Default.Save();int time = 1;try{time = int.Parse(textBox2.Text.ToString());}catch { }t.Interval=time*1000;}public void theout(object source, System.Timers.ElapsedEventArgs e){//MessageBox.Show("OK!");// string str=HttpGet(textBox1.Text.ToString(),"");webBrowser1.Navigate(textBox1.Text.ToString());num++;this.Invoke((EventHandler)(delegate{label1.Text = "自動同步" + num + "次";}));}CookieContainer cookie = new CookieContainer();private string HttpPost(string Url, string postDataStr){HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);request.Method = "POST";request.ContentType = "application/x-www-form-urlencoded";request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);request.CookieContainer = cookie;Stream myRequestStream = request.GetRequestStream();StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));myStreamWriter.Write(postDataStr);myStreamWriter.Close();HttpWebResponse response = (HttpWebResponse)request.GetResponse();response.Cookies = cookie.GetCookies(response.ResponseUri);Stream myResponseStream = response.GetResponseStream();StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));string retString = myStreamReader.ReadToEnd();myStreamReader.Close();myResponseStream.Close();return retString;}public string HttpGet(string Url, string postDataStr){HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);request.Method = "GET";request.ContentType = "text/html;charset=UTF-8";HttpWebResponse response = (HttpWebResponse)request.GetResponse();Stream myResponseStream = response.GetResponseStream();StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));string retString = myStreamReader.ReadToEnd();myStreamReader.Close();myResponseStream.Close();return retString;}private void Form1_FormClosing(object sender, FormClosingEventArgs e){this.WindowState = FormWindowState.Minimized;e.Cancel = true; }private void 退出ToolStripMenuItem_Click(object sender, EventArgs e){Settings1.Default.url = textBox1.Text.ToString();Settings1.Default.num = textBox2.Text.ToString();Settings1.Default.Save();// 關閉所有的線程this.Dispose();this.Close();}} }
總結
以上是生活随笔為你收集整理的C#源码刷新网页 最小化托盘http get和post请求配置保存版权时间限制定时调用 单实例运行,如果已经运行则激活窗口到最前显示的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ESP8266作为无线串口设置
- 下一篇: 树莓派基本配置