首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

Process 后, 怎么获取打开窗口的句柄

2012-08-30 
Process 后, 如何获取打开窗口的句柄?C# codemyProcess.StartInfo.UseShellExecute falsemyProcess.Sta

Process 后, 如何获取打开窗口的句柄?

C# code
myProcess.StartInfo.UseShellExecute = false;                myProcess.StartInfo.FileName = txt_ClientPath.Text;                myProcess.StartInfo.CreateNoWindow = true;                myProcess.Start();


[解决办法]
C# code
using System;using System.Diagnostics;using System.Runtime.InteropServices;using System.Text;namespace Text{    public class Program    {        [DllImport("user32.dll")]        static extern IntPtr GetTopWindow(IntPtr hWnd);        [DllImport("user32.dll")]        static extern Int32 GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);        [DllImport("user32.dll")]        static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);        [DllImport("user32.dll")]        static extern IntPtr GetWindow(IntPtr hWnd, UInt32 uCmd);        [DllImport("user32.dll")]        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);        private static readonly UInt32 GW_HWNDNEXT = 2;        static Int32 Run()        {            Process myProcess = new Process();            myProcess.StartInfo.UseShellExecute = false;            myProcess.StartInfo.FileName = "notepad.exe";            myProcess.StartInfo.CreateNoWindow = true;            myProcess.Start();            myProcess.WaitForExit(2000);            return myProcess.Id;        }        static IntPtr GetWnd(Int32 pID,String className, String text)        {            IntPtr h = GetTopWindow(IntPtr.Zero);            while (h != IntPtr.Zero)            {                UInt32 newID;                GetWindowThreadProcessId(h, out newID);                if (newID == pID)                {                    StringBuilder sbClassName = new StringBuilder(200);                    StringBuilder sbText = new StringBuilder(200);                    GetClassName(h, sbClassName, 200);                    GetWindowText(h, sbText, 200);                    if (sbClassName.ToString().IndexOf(className,StringComparison.CurrentCultureIgnoreCase) >= 0 &&                         sbText.ToString().IndexOf(text,StringComparison.CurrentCultureIgnoreCase) >= 0)                    {                        break;                    }                }                h = GetWindow(h, GW_HWNDNEXT);            }            return h;        }        static void Main(string[] args)        {            Console.WriteLine(GetWnd(Run(), "Notepad", "无标题 - 记事本"));            Console.ReadKey();        }    }} 

热点排行