var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-333696-1']); _gaq.push(['_trackPageview']); _gaq.push(['_trackPageLoadTime']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
  • 2010年02月01日

    Windows界面自动化等待(实现)

    分类:

    前文从理论上阐述了等待的一种判断,恰逢新年到来,现在放出具体实现代码。

     

    [C#]

    using System.Runtime.InteropServices;

    using System.Diagnostics;

    using System.Threading;

     

            internal static class NativeMethods

            {

                [DllImport("user32.dll")]

                internal static extern int GetWindowThreadProcessId(IntPtr hWnd, ref int processID);

            }

     

            public static void SyncUIThread(IntPtr hwnd, int mins)

            {

                int parentProcessID = 0;

                int threadID = 0;

                threadID = NativeMethods.GetWindowThreadProcessId(hwnd, ref parentProcessID);

                if(0 == threadID)

                    throw new ThreadStateException("Thread ID doesn't exit");

     

                Process tProcess = null;

                ProcessThreadCollection allThreads = null;

                ProcessThread tThread = null;

                int Pindex =0;

     

                DateTime EndTime = DateTime.Now.AddMinutes(mins);

                while (EndTime > DateTime.Now)

                {

                    tProcess = Process.GetProcessById(parentProcessID);

                    allThreads = tProcess.Threads;

                    for (; Pindex < allThreads.Count;++Pindex)

                    {

                        if (threadID == allThreads[Pindex].Id)

                        {

                            tThread = allThreads[Pindex];

                            break;

                        }

                    }

     

                    if (tThread != null && Pindex != allThreads.Count)

                    {

                        if (tThread.ThreadState == System.Diagnostics.ThreadState.Wait && tThread.WaitReason == System.Diagnostics.ThreadWaitReason.UserRequest)

                            return;

                    }

                    else throw new ThreadStateException("Thread ID doesn't exit");

                }

     

                throw new TimeoutException(mins + " minutes time out!");

               

            }

        }

    分享到: