.Net 獲取每個 Process 的 CPU及RAM 使用率 (PerformanceCounter)

使用 "效能計數器" 取得 CPU 使用率,但此方法如果有相同名稱,就無法取得所要項目的使用率。

程式碼如下:

using System;
using System.Diagnostics;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            UsingProcess("OUTLOOK");
        }

        static void UsingProcess(string pname)
        {
            using (var pro = Process.GetProcessesByName(pname)[0])
            {
                PerformanceCounter pf = new PerformanceCounter(); //性能計數器
                pf.CategoryName = "Process";
                pf.CounterName = "% Processor Time";
                pf.InstanceName = pro.ProcessName;
                pf.MachineName = ".";

                while (true)
                {
                    Console.WriteLine("RAM:" + (Convert.ToInt64(pro.WorkingSet64.ToString()) / 1024).ToString() + " CPU:" + Math.Round(pf.NextValue(), 2).ToString() + "%");
                    System.Threading.Thread.Sleep(1000);
                }
            }
        }
    }
}

  2012-06-04      ez      .NET
.Net 獲取每個 Process 的 CPU 使用率 (TotalProcessorTime)

.Net 並無法直接取得 Process 的 CPU使用率,所以利用 Process 在某時間區段內,CPU的使用時間來計算,即可得到 CPU 使用率。

CPU使用率 = 某時間取段 CPU 使用時間 / CPU 邏輯數量 程式碼如下:

using System;
using System.Diagnostics;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            UsingProcess("taskmgr");
        }

        static void UsingProcess(string pname)
        {
            using (var pro = Process.GetProcessesByName(pname)[0])
            {
                int interval = 1000; //間格時間
                while (true)
                {
                    var ProcessorTime = pro.TotalProcessorTime;
                    System.Threading.Thread.Sleep(interval);
                    var value = (pro.TotalProcessorTime - ProcessorTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
                    Console.WriteLine(value);
                }
            }
        }
    }
}

  2012-05-04      ez      .NET
.Net 檔案名稱包含特殊字元去除

假如要儲存的檔案名稱,包含特殊字元會造成無法儲存,只需透過 Path.InvalidPathChars 即可查出特殊字元,就可去除瞜。

foreach (char c in Path.InvalidPathChars)
        DatName = "檔案名稱".Replace(c.ToString(), "").Trim();

  2012-04-18      ez      .NET
.Net 擷取螢幕 Print Screen 螢幕畫面功能

透過 Graphics 中的 CopyFromScreen 即可達到複製螢幕功能!

全螢幕擷取到檔案:

            Bitmap myImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics g = Graphics.FromImage(myImage);
            g.CopyFromScreen(new Point(0,0), new Point(0, 0), new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height));
            IntPtr dc1 = g.GetHdc();
            g.ReleaseHdc(dc1);
            myImage.Save(@"c:\screen.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);

  2012-04-18      ez      .NET
.Net 取得某 Process 的使用者名稱

帶入 Process ID 取得使用者名稱:

public string GetProcessOwner(int processId)
{
    string query = "Select * From Win32_Process Where ProcessID = " + processId;
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
    ManagementObjectCollection processList = searcher.Get(); 

    foreach (ManagementObject obj in processList)
    {
        string[] argList = new string[] { string.Empty, string.Empty };
        int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
        if (returnVal == 0)
        {
            // return DOMAIN\user
            return argList[1] + "\\" + argList[0];
        }
    } 

    return "NO OWNER";
}

  2012-06-04      ez      .NET
.Net 產生 MD5 加密

方式一:效率較快!

        /// <summary>
        /// 加密
        /// </summary>        
        /// <param name="original">字串</param>
        /// <returns>回傳加密結果</returns>
        public string Encrypt(string Str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] bytes = md5.ComputeHash(Encoding.Default.GetBytes(Str));
            return BitConverter.ToString(bytes).Replace("-", string.Empty);
        }

  2012-08-22      ez      .NET
.Net 利用 FreeImage 讀取更多圖片格式 EXR,HDR,ICO,PCX,RAW...

首先下載 FreeImage:

本地下載:FreeImage

官方下載:http://freeimage.sourceforge.net/

將 FreeImageNET.dll 加入參考,即可開始利用 FreeImage 讀寫圖檔。

//讀出PCX圖檔到Image
FREE_IMAGE_FORMAT FIF = FREE_IMAGE_FORMAT.FIF_PCX;
Image IMG = FreeImage.LoadBitmap("檔案路徑", FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref FIF);

//讀出BMP圖檔到Image
FREE_IMAGE_FORMAT FIF = FREE_IMAGE_FORMAT.FIF_BMP;
Image IMG = FreeImage.LoadBitmap("檔案路徑", FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref FIF);

官方有提供 Sample 喔,自己研究吧!


  2012-06-20      ez      .NET
.Net 控制滑鼠

.Net 已經內建控制滑鼠位置的指令:

Cursor.Position = new Point(30, 60); //X Y軸位置

如果要點擊滑鼠就需要透過WinAPI才能達到:

首先建立一個Class:

using System.Threading;
using System.Runtime.InteropServices;
using System;

namespace Test
{
    static public class Mouse
    {
        [DllImport("user32.dll", SetLastError = true)]
        public static extern Int32 SendInput(Int32 cInputs, ref INPUT pInputs, Int32 cbSize);

        [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 28)]
        public struct INPUT
        {
            [FieldOffset(0)]
            public INPUTTYPE dwType;
            [FieldOffset(4)]
            public MOUSEINPUT mi;
            [FieldOffset(4)]
            public KEYBOARDINPUT ki;
            [FieldOffset(4)]
            public HARDWAREINPUT hi;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct MOUSEINPUT
        {
            public Int32 dx;
            public Int32 dy;
            public Int32 mouseData;
            public MOUSEFLAG dwFlags;
            public Int32 time;
            public IntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct KEYBOARDINPUT
        {
            public Int16 wVk;
            public Int16 wScan;
            public KEYBOARDFLAG dwFlags;
            public Int32 time;
            public IntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct HARDWAREINPUT
        {
            public Int32 uMsg;
            public Int16 wParamL;
            public Int16 wParamH;
        }

        public enum INPUTTYPE : int
        {
            Mouse = 0,
            Keyboard = 1,
            Hardware = 2
        }

        [Flags()]
        public enum MOUSEFLAG : int
        {
            MOVE = 0x1,
            LEFTDOWN = 0x2,
            LEFTUP = 0x4,
            RIGHTDOWN = 0x8,
            RIGHTUP = 0x10,
            MIDDLEDOWN = 0x20,
            MIDDLEUP = 0x40,
            XDOWN = 0x80,
            XUP = 0x100,
            VIRTUALDESK = 0x400,
            WHEEL = 0x800,
            ABSOLUTE = 0x8000
        }

        [Flags()]
        public enum KEYBOARDFLAG : int
        {
            EXTENDEDKEY = 1,
            KEYUP = 2,
            UNICODE = 4,
            SCANCODE = 8
        }
    }
}

  2012-06-04      ez      .NET
.Net 控制鍵盤

利用 SendKeys.Send 即可 輸入文字 或 發送某個按鍵。

SendKeys.Send("文字"); //發送文字

SendKeys.Send("{ENTER}"); //發送Enter按鍵

  2012-05-04      ez      .NET