運行結果:
using System;using System.Drawing;using System.Text;using NSoup;using NSoup.Nodes;using System.IO;using System.Net;using System.Text.RegularExpressions;using System.Windows.Forms;
namespace Pneumonia{ public partial class MainForm : DevComponents.DotNetBar.OfficeForm { static string confirmedCount, suspectedCount, deadCount, curedCount, updateTime,dataUpdateTime; static string url = "https://3g.dxy.cn/newh5/view/pneumonia"; static int count = 0; static Document doc; public MainForm(){ this.EnableGlass = false; InitializeComponent(); this.SizeChanged += new Resize(this).Form1_Resize; //窗口自適應代碼 } private void MainForm_Load(object sender, EventArgs e){ timer1.Enabled = true; timer1.Interval = 1; timer1.Start(); WebClient wc = new WebClient(); byte[] htmlData = wc.DownloadData(url); string html = Encoding.UTF8.GetString(htmlData); logWrite(html);//將網(wǎng)頁(yè)內容寫(xiě)入txt文件,以方便查看 toolStripStatusLabel1.Text = DateTime.Now.ToString(); } private void timer1_Tick(object sender, EventArgs e){ dataUpdateTime = DateTime.Now.ToString(); count++; timer1.Interval = 300000; GetData(); lbl1.Text = "? 病毒: " + regularMatchStr("getStatisticsService", "virus\":\"(.+?)\","); lbl2.Text = "? 傳染源: " + regularMatchStr("getStatisticsService", "infectSource\":\"(.+?)\","); lbl3.Text = "? 傳播途徑: " + regularMatchStr("getStatisticsService", "passWay\":\"(.+?)\","); lbl4.Text ="? "+regularMatchStr("getStatisticsService", "remark1\":\"(.+?)\","); lbl5.Text ="? "+regularMatchStr("getStatisticsService", "remark2\":\"(.+?)\","); Image map =UrlToImage("https://img1.dxycdn.com/2020/0201/450/3394153392393266839-135.png"); pictureBox1.Image = map; Image chart = UrlToImage("https://img1.dxycdn.com/2020/0201/693/3394145745204021706-135.png"); pictureBox2.Image = chart; updateTimeLbl.Text = "截至 " + updateTime + " 全國數據統計"; confirmedLbl.Text = confirmedCount; suspectedLbl.Text = suspectedCount; deadLbl.Text = deadCount; curedLbl.Text = curedCount; }
public static void GetData(){ //直接通過(guò)url來(lái)獲取Document對象 doc = NSoupClient.Connect(url).Get(); //先獲取id為artContent的元素,再獲取所有的p標簽 updateTime = ConvertStringToDateTime(regularMatchStr("getStatisticsService", "modifyTime\":(.+?),")).ToString(); confirmedCount = regularMatchStr("getStatisticsService", "confirmedCount\":(.+?),"); suspectedCount = regularMatchStr("getStatisticsService", "suspectedCount\":(.+?),"); deadCount = regularMatchStr("getStatisticsService", "deadCount\":(.+?),"); curedCount = regularMatchStr("getStatisticsService", "curedCount\":(.+?),"); } #region 下載圖片到Image public static Image UrlToImage(string url){ WebClient mywebclient = new WebClient(); byte[] Bytes = mywebclient.DownloadData(url); using (MemoryStream ms = new MemoryStream(Bytes)) { Image outputImg = Image.FromStream(ms); return outputImg; } } #endregion public static DateTime ConvertStringToDateTime(string timeStamp){ DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } public static string regularMatchStr(string elementId, string regex){ Element p = doc.GetElementById(elementId); Regex reg = new Regex(regex, RegexOptions.IgnoreCase); //例如我想提取line中的NAME值 Match match = reg.Match(p.Html()); string value = match.Groups[1].Value; return value; } public static void logWrite(string Message){ if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\log.txt")) File.Create(AppDomain.CurrentDomain.BaseDirectory + "\\log.txt").Close(); string fileName = AppDomain.CurrentDomain.BaseDirectory + "\\log.txt"; string content = DateTime.Now.ToLocalTime() + Message + "\r\n"; StreamWriter sw = new StreamWriter(fileName, true); sw.Write(content); sw.Close(); sw.Dispose(); }
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e){ if (e.Button == MouseButtons.Left)//判斷鼠標的按鍵 { //點(diǎn)擊時(shí)判斷form是否顯示,顯示就隱藏,隱藏就顯示 if (this.WindowState == FormWindowState.Normal) { this.WindowState = FormWindowState.Minimized; this.Hide(); } else if (this.WindowState == FormWindowState.Minimized) { this.Show(); this.WindowState = FormWindowState.Normal; this.Activate(); } } else if (e.Button == MouseButtons.Right) { //右鍵退出事件 if (MessageBox.Show("是否需要關(guān)閉程序?", "提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)//出錯提示 { //關(guān)閉窗口 DialogResult = DialogResult.No; Dispose(); Close(); } }
}
private void timer2_Tick(object sender, EventArgs e){ toolStripStatusLabel1.Text = DateTime.Now.ToString() + " 刷新次數 : " + count + " 最新刷新時(shí)間 :" + dataUpdateTime; }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e){ if (MessageBox.Show("是否確認退出程序?", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) { // 關(guān)閉所有的線(xiàn)程 this.Dispose(); this.Close(); } else { e.Cancel = true; } }
private void MainForm_SizeChanged(object sender, EventArgs e){ //判斷是否選擇的是最小化按鈕 if (WindowState == FormWindowState.Minimized) { //隱藏任務(wù)欄區圖標 this.ShowInTaskbar = false; //圖標顯示在托盤(pán)區 notifyIcon1.Visible = true; } }
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e) { if (MessageBox.Show("是否確認退出程序?", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) { // 關(guān)閉所有的線(xiàn)程 this.Dispose(); this.Close(); } }
private void 顯示ToolStripMenuItem_Click(object sender, EventArgs e) { WindowState = FormWindowState.Normal; }
}}
resize類(lèi)
using System;using System.Collections.Generic;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;
namespace Pneumonia{ class Resize { private MainForm _form;
public Resize(MainForm form) { int count = form.Controls.Count * 2 + 2; float[] factor = new float[count]; int i = 0; factor[i++] = form.Size.Width; factor[i++] = form.Size.Height; foreach (Control ctrl in form.Controls) { factor[i++] = ctrl.Location.X / (float)form.Size.Width; factor[i++] = ctrl.Location.Y / (float)form.Size.Height; ctrl.Tag = ctrl.Size; } form.Tag = factor; this._form = form; }
public void Form1_Resize(object sender, EventArgs e) { float[] scale = (float[])this._form.Tag; int i = 2; foreach (Control ctrl in this._form.Controls) //panel的長(cháng)寬增長(cháng)到一個(gè)固定的值就不會(huì )再增長(cháng)了,原因:Panel的寬和高上限是65535像素(https://blog.csdn.net/dufangfeilong/article/details/41805073?utm_source=blogxgwz5) { ctrl.Left = (int)(this._form.Size.Width * scale[i++]); ctrl.Top = (int)(this._form.Size.Height * scale[i++]); ctrl.Width = (int)(this._form.Size.Width / (float)scale[0] * ((Size)ctrl.Tag).Width); ctrl.Height = (int)(this._form.Size.Height / (float)scale[1] * ((Size)ctrl.Tag).Height); } } }}
C# Winform控件自適應窗體大?。?span style="color: rgb(255, 0, 0);">方法1(推薦)
參考鏈接:https://www.cnblogs.com/PER10/p/11541568.html
需求:當窗體尺寸動(dòng)態(tài)改變時(shí),窗體中的各種控件(包括Panel以及Panel中的子控件)可以動(dòng)態(tài)調節自身大小,以適應窗體內容比例。
方法:
第一步,新建一個(gè)類(lèi),代碼如下:
class Resize { private Form _form;
public Resize(Form form) { int count = form.Controls.Count * 2 + 2; float[] factor = new float[count]; int i = 0; factor[i++] = form.Size.Width; factor[i++] = form.Size.Height; foreach (Control ctrl in form.Controls) { factor[i++] = ctrl.Location.X / (float)form.Size.Width; factor[i++] = ctrl.Location.Y / (float)form.Size.Height; ctrl.Tag = ctrl.Size; } form.Tag = factor; this._form = form; }
public void Form1_Resize(object sender, EventArgs e) { float[] scale = (float[])this._form.Tag; int i = 2; foreach (Control ctrl in this._form.Controls) //panel的長(cháng)寬增長(cháng)到一個(gè)固定的值就不會(huì )再增長(cháng)了,原因:Panel的寬和高上限是65535像素(https://blog.csdn.net/dufangfeilong/article/details/41805073?utm_source=blogxgwz5) { ctrl.Left = (int)(this._form.Size.Width * scale[i++]); ctrl.Top = (int)(this._form.Size.Height * scale[i++]); ctrl.Width = (int)(this._form.Size.Width / (float)scale[0] * ((Size)ctrl.Tag).Width); ctrl.Height = (int)(this._form.Size.Height / (float)scale[1] * ((Size)ctrl.Tag).Height); } } } 第二步,在Form的初始化函數中使用這個(gè)類(lèi): public Form_StockCount() { InitializeComponent();
this.SizeChanged += new Resize(this).Form1_Resize; //窗口自適應代碼 }C# Winform窗體和控件自適應大?。悍椒?
1.在項目中創(chuàng )建類(lèi)AutoSizeForm
AutoSizeForm.cs文件代碼:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace CSharpFormApplication{ class AutoResizeForm { //(1).聲明結構,只記錄窗體和其控件的初始位置和大小。 public struct controlRect { public int Left; public int Top; public int Width; public int Height; } //(2).聲明 1個(gè)對象 //注意這里不能使用控件列表記錄 List nCtrl;,因為控件的關(guān)聯(lián)性,記錄的始終是當前的大小。 // public List oldCtrl= new List();//這里將西文的大于小于號都過(guò)濾掉了,只能改為中文的,使用中要改回西文 public List<controlRect> oldCtrl = new List<controlRect>(); int ctrlNo = 0;//1; //(3). 創(chuàng )建兩個(gè)函數 //(3.1)記錄窗體和其控件的初始位置和大小, public void controllInitializeSize(Control mForm) { controlRect cR; cR.Left = mForm.Left; cR.Top = mForm.Top; cR.Width = mForm.Width; cR.Height = mForm.Height; oldCtrl.Add(cR);//第一個(gè)為"窗體本身",只加入一次即可 AddControl(mForm);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用 //this.WindowState = (System.Windows.Forms.FormWindowState)(2);//記錄完控件的初始位置和大小后,再最大化 //0 - Normalize , 1 - Minimize,2- Maximize } private void AddControl(Control ctl) { foreach (Control c in ctl.Controls) { //**放在這里,是先記錄控件的子控件,后記錄控件本身 //if (c.Controls.Count > 0) // AddControl(c);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用 controlRect objCtrl; objCtrl.Left = c.Left; objCtrl.Top = c.Top; objCtrl.Width = c.Width; objCtrl.Height = c.Height; oldCtrl.Add(objCtrl); //**放在這里,是先記錄控件本身,后記錄控件的子控件 if (c.Controls.Count > 0) AddControl(c);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用 } } //(3.2)控件自適應大小, public void controlAutoSize(Control mForm) { if (ctrlNo == 0) { //*如果在窗體的Form1_Load中,記錄控件原始的大小和位置,正常沒(méi)有問(wèn)題,但要加入皮膚就會(huì )出現問(wèn)題,因為有些控件如dataGridView的的子控件還沒(méi)有完成,個(gè)數少 //*要在窗體的Form1_SizeChanged中,第一次改變大小時(shí),記錄控件原始的大小和位置,這里所有控件的子控件都已經(jīng)形成 controlRect cR; // cR.Left = mForm.Left; cR.Top = mForm.Top; cR.Width = mForm.Width; cR.Height = mForm.Height; cR.Left = 0; cR.Top = 0; cR.Width = mForm.PreferredSize.Width; cR.Height = mForm.PreferredSize.Height;
oldCtrl.Add(cR);//第一個(gè)為"窗體本身",只加入一次即可 AddControl(mForm);//窗體內其余控件可能嵌套其它控件(比如panel),故單獨抽出以便遞歸調用 } float wScale = (float)mForm.Width / (float)oldCtrl[0].Width;//新舊窗體之間的比例,與最早的舊窗體 float hScale = (float)mForm.Height / (float)oldCtrl[0].Height;//.Height; ctrlNo = 1;//進(jìn)入=1,第0個(gè)為窗體本身,窗體內的控件,從序號1開(kāi)始 AutoScaleControl(mForm, wScale, hScale);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用 } private void AutoScaleControl(Control ctl, float wScale, float hScale) { int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0; //int ctrlNo = 1;//第1個(gè)是窗體自身的 Left,Top,Width,Height,所以窗體控件從ctrlNo=1開(kāi)始 foreach (Control c in ctl.Controls) { //**放在這里,是先縮放控件的子控件,后縮放控件本身 //if (c.Controls.Count > 0) // AutoScaleControl(c, wScale, hScale);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用 ctrLeft0 = oldCtrl[ctrlNo].Left; ctrTop0 = oldCtrl[ctrlNo].Top; ctrWidth0 = oldCtrl[ctrlNo].Width; ctrHeight0 = oldCtrl[ctrlNo].Height; //c.Left = (int)((ctrLeft0 - wLeft0) * wScale) + wLeft1;//新舊控件之間的線(xiàn)性比例 //c.Top = (int)((ctrTop0 - wTop0) * h) + wTop1; c.Left = (int)((ctrLeft0) * wScale);//新舊控件之間的線(xiàn)性比例??丶恢弥幌鄬τ诖绑w,所以不能加 + wLeft1 c.Top = (int)((ctrTop0) * hScale);// c.Width = (int)(ctrWidth0 * wScale);//只與最初的大小相關(guān),所以不能與現在的寬度相乘 (int)(c.Width * w); c.Height = (int)(ctrHeight0 * hScale);// ctrlNo++;//累加序號 //**放在這里,是先縮放控件本身,后縮放控件的子控件 if (c.Controls.Count > 0) AutoScaleControl(c, wScale, hScale);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用
if (ctl is DataGridView) { DataGridView dgv = ctl as DataGridView; Cursor.Current = Cursors.WaitCursor;
int widths = 0; for (int i = 0; i < dgv.Columns.Count; i++) { dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells); // 自動(dòng)調整列寬 widths += dgv.Columns[i].Width; // 計算調整列后單元列的寬度和 } if (widths >= ctl.Size.Width) // 如果調整列的寬度大于設定列寬 dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; // 調整列的模式 自動(dòng) else dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; // 如果小于 則填充
Cursor.Current = Cursors.Default; } }
} } } 2.在要自適應大小的Form中自定義全局類(lèi)對象 AutoResizeForm asc = new AutoResizeForm(); 3.在要自適應大小的Form的load事件和SizeChange事件中執行對象方法 private void WidgetAutoResizeForm_Load(object sender, EventArgs e) { asc.controllInitializeSize(this); }
private void WidgetAutoResizeForm_SizeChanged(object sender, EventArgs e) { asc.controlAutoSize(this); } From窗體代碼: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;
namespace CSharpFormApplication{ public partial class WidgetAutoResizeForm : Form { AutoResizeForm asc = new AutoResizeForm(); public WidgetAutoResizeForm() { InitializeComponent(); }
private void WidgetAutoResizeForm_Load(object sender, EventArgs e) { asc.controllInitializeSize(this); }
private void WidgetAutoResizeForm_SizeChanged(object sender, EventArgs e) { asc.controlAutoSize(this); } }} https://www.cnblogs.com/AmatVictorialCuram/p/5066670.html
WinForm 之 窗口最小化到托盤(pán)及右鍵圖標顯示菜單
參考鏈接:https://www.cnblogs.com/xinaixia/p/6216670.html
聯(lián)系客服