桌面置頂顯示服務器信息
- 2021 年 1 月 29 日
- 筆記
前言
在手頭上做的項目很多,管理的服務器也很多。
一個項目最少也得2+以上的服務器。
在各個項目部署的時候,要來回切換不同的服務器。
搞着搞着就不知道當前遠程在哪台服務器了。
所以希望在電腦桌面上可以很快的知道當前遠程連接到了哪台服務器
設置背景桌面
最開始的時候,我們在每台服務器的背景桌面圖片。
在圖片上把當前服務器信息都做到圖片上,
然後把這個圖片設置為服務器的背景圖片。
這樣一遠程到服務器上,就可以知道當前是哪台服務器了
然而這種方式有很大的弊端。
就是當我把一些應用最大化之後,背景圖片就已經完全看不到了。
而且只能顯示一些靜態信息。比如機器名,系統版本,IP
還有就是我們99%的時間是看不到背景圖片的。
所以這種方式有用,但是也很雞肋。
實現功能
所以在休息的時候,自己有些WinForm的知識。
打算開發一個應用,可以在電腦桌面的右下角
實時顯示當前服務器的信息。
比如機器名,系統版本,登錄用戶,內存,CPU,磁盤,IP
當有應用最大化後,這些信息也在最頂層顯示出來
效果圖如下
關鍵代碼
設置Form
this.BackColor = System.Drawing.Color.White;//設置背景
this.ClientSize = new System.Drawing.Size(1024, 768);//界面大小
this.ControlBox = false;//不顯示標題欄
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;//無邊框
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.ShowIcon = false;
this.ShowInTaskbar = false;//不顯示在任務欄
this.TopMost = true;//置頂
this.TransparencyKey = System.Drawing.Color.White;//透明
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;//最大化顯示
獲取服務器信息
string strQuery = "select Caption,CSName,TotalVisibleMemorySize from win32_OperatingSystem";
SelectQuery queryOS = new SelectQuery(strQuery);
string Caption = "";
string CSName = "";
ulong TotalVisibleMemorySize = 0;
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(queryOS))
{
using (var queryResult = searcher.Get())
{
foreach (var os in queryResult)
{
Caption = (string)os["Caption"];
CSName = (string)os["CSName"];
TotalVisibleMemorySize = (ulong)os["TotalVisibleMemorySize"];
}
}
}
return new OSInfoModel() { Caption = Caption, CSName = CSName, TotalVisibleMemorySize = TotalVisibleMemorySize };
獲取更多服務器信息,請參考
//docs.microsoft.com/en-us/previous-versions/aa394084(v=vs.85)
獲取IP
var listIP = new List<String>();
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
var ipStr = ip.Address.ToString();
if (!(ipStr.StartsWith("169") || ipStr.EndsWith(".1") || ipStr.EndsWith(".255")))
listIP.Add(ipStr);
}
}
}
}
return String.Join(Environment.NewLine, listIP);
獲取動態信息
//獲取CPU使用率
this.CpuPC = new PerformanceCounter("Processor", "% Processor Time", "_Total");
this.CpuPC.NextValue()
//獲取可用內存
this.RamPC = new PerformanceCounter("Memory", "Available KBytes");
this.RamPC.NextValue()
//獲取磁盤性能
this.DiskPC = new PerformanceCounter("PhysicalDisk", "% Idle Time", "_Total");
this.DiskPC.NextValue()
關於獲取更多服務器性能信息。可參考「性能監視器”