Demo:Windows Mobile 6.5 进程管理

楼主
Demo:Windows Mobile 6.5 进程管理
[CODE]//------------------------------------------------------------------------
// <copyright file="ProcessInfo.cs" company="Yaping Xin">
//     Copyright (c) Yaping Xin. All rights reserved.
// </copyright>
// <Description>Process management.</Description>
//------------------------------------------------------------------------
namespace MobileAutomation.PhoneCore.Common
{
    using System;
    using System.Collections;
    using MobileAutomation.PhoneCore.NativeMethods;
    using MobileAutomation.PhoneCore.NativeStructures;

    /// <summary>
    /// Description for Process.
    /// </summary>
    public class ProcessInfo
    {
        #region Private Data Members
        /// <summary>Process Name</summary>
        private string processName;

        /// <summary>Process handle</summary>
        private IntPtr handle;

        /// <summary>Process thread count</summary>
        private int threadCount;

        /// <summary>Process base address</summary>
        private int baseAddress;
        #endregion

        #region Initialization
        /// <summary>
        /// Initializes a new instance of the ProcessInfo class.
        /// </summary>
        public ProcessInfo()
        {
        }

        /// <summary>
        /// Initializes a new instance of the ProcessInfo class with parameters.
        /// </summary>
        /// <param name="handle">Process handle</param>
        /// <param name="processName">Process Name</param>
        /// <param name="threadCount">Process thread count</param>
        /// <param name="baseAddress">Process base address</param>
        public ProcessInfo(IntPtr handle, string processName, int threadCount, int baseAddress)
        {
            this.handle = handle;
            this.processName = processName;
            this.threadCount = threadCount;
            this.baseAddress = baseAddress;
        }
        #endregion

        #region Public Properties
        /// <summary>
        /// Gets Process Name property
        /// </summary>
        public string ProcessName
        {
            get { return this.processName; }
        }

        /// <summary>
        /// Gets Base Address property
        /// </summary>
        public int BaseAddress
        {
            get { return this.baseAddress; }
        }

        /// <summary>
        /// Gets Thread Count property
        /// </summary>
        public int ThreadCount
        {
            get { return this.threadCount; }
        }

        /// <summary>
        /// Gets Handle property
        /// </summary>
        public IntPtr Handle
        {
            get { return this.handle; }
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// Gets process list
        /// </summary>
        /// <returns>process list</returns>
        public static ProcessInfo[] GetProcesses()
        {
            ArrayList processList = new ArrayList();
            IntPtr handle = ToolHelp.CreateToolhelp32Snapshot((uint)(TH32CS.SnapProcess | TH32CS.SnapNoHeaps), 0);
            if ((int)handle > 0)
            {
                try
                {
                    ProcessEntry32 current;
                    ProcessEntry32 processEntry32 = new ProcessEntry32();

                    // Get byte array to pass to the API calls
                    byte[] bytes = processEntry32.ToByteArray();

                    // Get the first process
                    int retval = ToolHelp.Process32First(handle, bytes);

                    while (retval == 1)
                    {
                        // Convert bytes to the class
                        current = new ProcessEntry32(bytes);

                        // New instance
                        ProcessInfo proc = new ProcessInfo(new IntPtr((int)current.PID), current.Name, (int)current.ThreadCount, (int)current.BaseAddress);

                        processList.Add(proc);
                        retval = ToolHelp.Process32Next(handle, bytes);
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("Exception in creating process list: " + e.Message);
                }

                ToolHelp.CloseToolhelp32Snapshot(handle);
                return (ProcessInfo[])processList.ToArray(typeof(ProcessInfo));
            }
            else
            {
                throw new Exception("Cannot create snapshot using toolhelp.dll");
            }
        }

        /// <summary>
        /// ToString() implementation.
        /// </summary>
        /// <returns>ToString() value</returns>
        public override string ToString()
        {
            return this.ProcessName;
        }

        /// <summary>
        /// Kill the process
        /// </summary>
        public void Kill()
        {
            IntPtr process;

            process = CoreDll.OpenProcess(CoreDll.ProcessTerminate, false, (int)this.Handle);

            if (process != (IntPtr)CoreDll.InvalidHandleValue)
            {
                CoreDll.TerminateProcess(process, 0);

                CoreDll.CloseHandle(process);
            }
        }
        #endregion
    }
}[/CODE]
1楼
相关的Native方法封装:ToolHelp.cs
[CODE]//------------------------------------------------------------------------
//
//     Copyright (c) Yaping Xin. All rights reserved.
//
// Helper class for Native Methods in ToolHelp.dll.
// http://msdn.microsoft.com/en-us/library/ms858621.aspx
//------------------------------------------------------------------------
namespace MobileAutomation.PhoneCore.NativeMethods
{
    using System;
    using System.Runtime.InteropServices;
    using MobileAutomation.PhoneCore.NativeStructures;

    ///
    /// Helper class for Native Methods in ToolHelp.dll
    /// Link: http://msdn.microsoft.com/en-us/library/ms858621.aspx
    ///
    public static class ToolHelp
    {
        ///
        /// This function takes a snapshot of the processes, heaps, modules, and threads used by the processes.
        /// Link: http://msdn.microsoft.com/en-us/library/aa911386.aspx
        /// [C++] HANDLE WINAPI CreateToolhelp32Snapshot(DWORD dwFlags, DWORD th32ProcessID);
        ///
        /// [in] Portions of the system to include in the snapshot. The following table shows possible values.
        /// [in] Process identifier.
        /// An open handle to the specified snapshot indicates success. INVALID_HANDLE_VALUE indicates failure.
        [DllImport("toolhelp.dll")]
        public static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processId);

        ///
        /// This function closes a handle to a snapshot.
        /// Link: http://msdn.microsoft.com/en-us/library/aa914612.aspx
        /// [C++] BOOL WINAPI CloseToolhelp32Snapshot(HANDLE hSnapshot);
        ///
        /// [in] Handle to a snapshot returned from the CreateToolhelp32Snapshot function.
        /// TRUE indicates success. FALSE indicates failure.
        [DllImport("toolhelp.dll")]
        public static extern int CloseToolhelp32Snapshot(IntPtr handle);

        ///
        /// This function retrieves information about the first process encountered in a system snapshot.
        /// Link: http://msdn.microsoft.com/en-us/library/aa915359.aspx
        /// [C++] BOOL WINAPI Process32First(HANDLE hSnapshot, LPPROCESSENTRY32 lppe);
        ///
        /// [in] Handle to the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.
        /// [out] Pointer to a PROCESSENTRY32 structure.
        /// TRUE indicates that the first entry of the process list has been copied to the buffer. FALSE indicates failure.
        [DllImport("toolhelp.dll")]
        public static extern int Process32First(IntPtr handle, byte[] pe);

        ///
        /// This function retrieves information about the next process recorded in a system snapshot.
        ///
        /// [in] Handle to the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.
        /// [out] Pointer to a PROCESSENTRY32 structure.
        /// TRUE indicates that the next entry of the process list has been copied to the buffer. FALSE indicates failure.
        [DllImport("toolhelp.dll")]
        public static extern int Process32Next(IntPtr handle, byte[] pe);
    }
}[/CODE]
2楼
相关的Native方法封装:CoreDll.cs
[CODE]//------------------------------------------------------------------------
// <copyright file="CoreDll.cs" company="Yaping Xin">
//     Copyright (c) Yaping Xin. All rights reserved.
// </copyright>
// <Description>Helper class for Native Methods in coredll.dll.</Description>
//------------------------------------------------------------------------
namespace MobileAutomation.PhoneCore.NativeMethods
{
    using System;
    using System.Runtime.InteropServices;
    using MobileAutomation.PhoneCore.NativeStructures;

    /// <summary>
    /// Helper class for Native Methods in coredll.dll
    /// </summary>
    public static class CoreDll
    {
        #region Const Definition
        /// <summary>const int PROCESS_TERMINATE = 1;</summary>
        public const int ProcessTerminate = 1;

        /// <summary>const int INVALID_HANDLE_VALUE = -1;</summary>
        public const int InvalidHandleValue = -1;
        #endregion

        #region Process Management
        /// <summary>
        /// This function creates a named or unnamed Mutex object.
        /// Link: http://msdn.microsoft.com/en-us/library/aa914601.aspx
        /// [C++] HANDLE CreateMutex(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCTSTR lpName);
        /// </summary>
        /// <param name="mutexAttributes">[in] Ignored. Must be NULL.</param>
        /// <param name="initialOwner">[in] Boolean that specifies the initial owner of the Mutex object.
        /// If this value is TRUE and the caller created the Mutex, the calling thread obtains ownership of the Mutex object.
        /// Otherwise, the calling thread does not obtain ownership of the Mutex.
        /// To determine if the caller created the Mutex, see the Return Values section.</param>
        /// <param name="name">[in] Long pointer to a null-terminated string specifying the name of the Mutex object.</param>
        /// <returns>A handle to the Mutex object indicates success.
        /// If the named Mutex object existed before the function call, the function returns a handle to the existing object,
        /// and GetLastError returns ERROR_ALREADY_EXISTS. Otherwise, the caller created the Mutex.
        /// NULL indicates failure. To get extended error information, call GetLastError.</returns>
        [DllImport("coredll.dll", EntryPoint = "CreateMutex", SetLastError = true)]
        public static extern IntPtr CreateMutex(SecurityAttributes mutexAttributes, bool initialOwner, string name);

        /// <summary>
        /// releases ownership of the specified mutex object.
        /// Link: http://msdn.microsoft.com/en-us/library/aa908800.aspx
        /// [C++] BOOL ReleaseMutex(HANDLE hMutex);
        /// </summary>
        /// <param name="mutex">[in] Handle to the mutex object. The CreateMutex function returns this handle.</param>
        /// <returns>Nonzero indicates success. Zero indicates failure. To get extended error information, call GetLastError.</returns>
        [DllImport("coredll.dll", EntryPoint = "ReleaseMutex", SetLastError = true)]
        public static extern bool ReleaseMutex(IntPtr mutex);
       
        /// <summary>
        /// This function puts the thread that created the specified window into the foreground and activates the window.
        /// Link: http://msdn.microsoft.com/en-us/library/aa923858.aspx
        /// [C++] BOOL SetForegroundWindow(HWND hWnd);
        /// Header: winuser.h
        /// Windows Embedded CE: Windows CE 1.0 and later
        /// Windows Mobile: Windows Mobile Version 5.0 and later
        /// </summary>
        /// <param name="window">[in] Handle to the window that should be activated and brought to the foreground. For more information, see the Remarks section.</param>
        /// <returns>Nonzero indicates that the window was brought to the foreground. Zero indicates that the window was not brought to the foreground. </returns>
        [DllImport("coredll.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]
        public static extern bool SetForegroundWindow(IntPtr window);

        /// <summary>
        /// This function returns a handle to an existing process object. When you finish with the handle, close it using the CloseHandle function.
        /// Link: http://msdn.microsoft.com/en-us/library/aa909175.aspx
        /// [C++] HANDLE OpenProcess(DWORD fdwAccess, BOOL fInherit, DWORD IDProcess);
        /// </summary>
        /// <param name="flags">[in] Not supported; set to zero.</param>
        /// <param name="inherit">[in] Not supported; set to FALSE.</param>
        /// <param name="pid">[in] Specifies the process identifier of the process to open.</param>
        /// <returns>An open handle to the specified process indicates success. NULL indicates failure. To get extended error information, call GetLastError. </returns>
        [DllImport("coredll.dll")]
        public static extern IntPtr OpenProcess(int flags, bool inherit, int pid);

        /// <summary>
        /// This function closes the specified process and all of its threads.
        /// Link: http://msdn.microsoft.com/en-us/library/aa908764.aspx
        /// [C++] BOOL TerminateProcess(HANDLE hProcess, DWORD uExitCode);
        /// </summary>
        /// <param name="processhandler">[in] Handle to the process to terminate. This is a handle returned from OpenProcess.</param>
        /// <param name="exitCode">[in] Specifies the exit code for the process and for all threads terminated as a result of this call.</param>
        /// <returns>Nonzero indicates success. Zero indicates failure. To get extended error information, call GetLastError.</returns>
        [DllImport("coredll.dll")]
        public static extern bool TerminateProcess(IntPtr processhandler, uint exitCode);
        #endregion

        /// <summary>
        /// Closes an open object handle.
        /// Link: http://msdn.microsoft.com/en-us/library/aa914720.aspx
        /// [C++] BOOL CloseHandle(HANDLE hObject);
        /// </summary>
        /// <param name="objectHandler">[in] HANDLE hObject: Handle to an open object.</param>
        /// <returns>BOOL: Nonzero indicates success. Zero indicates failure. To get extended error information, call GetLastError.</returns>
        [DllImport("coredll.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CloseHandle(IntPtr objectHandler);

    }
}[/CODE]
3楼
相关结构定义:ProcessEntry32.cs
[CODE]//------------------------------------------------------------------------
// <copyright file="ProcessEntry32.cs" company="Yaping Xin">
//     Copyright (c) Yaping Xin. All rights reserved.
// </copyright>
// <Description>This class defines the PROCESSENTRY32 structure.</Description>
// <Link>http://msdn.microsoft.com/en-us/library/aa911518.aspx</Link>
//------------------------------------------------------------------------
namespace MobileAutomation.PhoneCore.NativeStructures
{
    using System;
    using System.Runtime.InteropServices;
    using System.Text;

    /// <summary>
    /// This class defines the PROCESSENTRY32 structure.
    /// Link: http://msdn.microsoft.com/en-us/library/aa911518.aspx
    /// Original Definition:
    /// typedef struct tagPROCESSENTRY32 {
    ///     DWORD dwSize;
    ///     DWORD cntUsage;
    ///     DWORD th32ProcessID;
    ///     DWORD th32DefaultHeapID;
    ///     DWORD th32ModuleID;
    ///     DWORD cntThreads;
    ///     DWORD th32ParentProcessID;
    ///     LONG  pcPriClassBase;
    ///     DWORD dwFlags;
    ///     TCHAR szExeFile[MAX_PATH];
    ///     DWORD th32MemoryBase;
    ///     DWORD th32AccessKey;
    /// } PROCESSENTRY32;
    /// typedef PROCESSENTRY32* PPROCESSENTRY32;
    /// typedef PROCESSENTRY32* LPPROCESSENTRY32;
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public class ProcessEntry32
    {
        #region constants for structure definition
        private const int SizeOffset = 0;
        private const int UsageOffset = 4;
        private const int ProcessIDOffset = 8;
        private const int DefaultHeapIDOffset = 12;
        private const int ModuleIDOffset = 16;
        private const int ThreadsOffset = 20;
        private const int ParentProcessIDOffset = 24;
        private const int PriClassBaseOffset = 28;
        private const int dwFlagsOffset = 32;
        private const int ExeFileOffset = 36;
        private const int MemoryBaseOffset = 556;
        private const int AccessKeyOffset = 560;
        private const int Size = 564;
        private const int MAX_PATH = 260;
        #endregion

        #region data members
        public uint dwSize;
        public uint cntUsage;
        public uint th32ProcessID;
        public uint th32DefaultHeapID;
        public uint th32ModuleID;
        public uint cntThreads;
        public uint th32ParentProcessID;
        public long pcPriClassBase;
        public uint dwFlags;
        public string szExeFile;
        public uint th32MemoryBase;
        public uint th32AccessKey;
        #endregion

        /// <summary>
        /// Default constructor
        /// </summary>
        public ProcessEntry32()
        {
        }

        /// <summary>
        /// create a PROCESSENTRY instance based on a byte array  
        /// </summary>
        /// <param name="aData">byte[] data</param>
        public ProcessEntry32(byte[] aData)
        {
            dwSize = GetUInt(aData, SizeOffset);
            cntUsage = GetUInt(aData, UsageOffset);
            th32ProcessID = GetUInt(aData, ProcessIDOffset);
            th32DefaultHeapID = GetUInt(aData, DefaultHeapIDOffset);
            th32ModuleID = GetUInt(aData, ModuleIDOffset);
            cntThreads = GetUInt(aData, ThreadsOffset);
            th32ParentProcessID = GetUInt(aData, ParentProcessIDOffset);
            pcPriClassBase = (long)GetUInt(aData, PriClassBaseOffset);
            dwFlags = GetUInt(aData, dwFlagsOffset);
            szExeFile = GetString(aData, ExeFileOffset, MAX_PATH);
            th32MemoryBase = GetUInt(aData, MemoryBaseOffset);
            th32AccessKey = GetUInt(aData, AccessKeyOffset);
        }

        #region Helper conversion functions
        // utility:  get a uint from the byte array
        private static uint GetUInt(byte[] aData, int Offset)
        {
            return BitConverter.ToUInt32(aData, Offset);
        }

        // utility:  set a uint int the byte array
        private static void SetUInt(byte[] aData, int Offset, int Value)
        {
            byte[] buint = BitConverter.GetBytes(Value);
            Buffer.BlockCopy(buint, 0, aData, Offset, buint.Length);
        }

        // utility:  get a ushort from the byte array
        private static ushort GetUShort(byte[] aData, int Offset)
        {
            return BitConverter.ToUInt16(aData, Offset);
        }

        // utility:  set a ushort int the byte array
        private static void SetUShort(byte[] aData, int Offset, int Value)
        {
            byte[] bushort = BitConverter.GetBytes((short)Value);
            Buffer.BlockCopy(bushort, 0, aData, Offset, bushort.Length);
        }

        // utility:  get a unicode string from the byte array
        private static string GetString(byte[] aData, int Offset, int Length)
        {
            String sReturn = Encoding.Unicode.GetString(aData, Offset, Length);
            return sReturn;
        }

        // utility:  set a unicode string in the byte array
        private static void SetString(byte[] aData, int Offset, string Value)
        {
            byte[] arr = Encoding.ASCII.GetBytes(Value);
            Buffer.BlockCopy(arr, 0, aData, Offset, arr.Length);
        }
        #endregion

        // create an initialized data array
        public byte[] ToByteArray()
        {
            byte[] aData;
            aData = new byte[Size];
            //set the Size member
            SetUInt(aData, SizeOffset, Size);
            return aData;
        }

        public string Name
        {
            get { return szExeFile.Substring(0, szExeFile.IndexOf('\0')); }
        }

        public ulong PID
        {
            get { return th32ProcessID; }
        }

        public ulong BaseAddress
        {
            get { return th32MemoryBase; }
        }

        public ulong ThreadCount
        {
            get { return cntThreads; }
        }
    }
}[/CODE]
4楼
Over. Have fun!

电脑版 Page created in 0.0781 seconds with 4 queries.