locked
Получение активного окна (Control) имеющего фокус из другого (рабочего) потока RRS feed

  • Общие обсуждения

  • День добрый, имеется обработчик события из рабочего потока, в нем необходимо получить окно из главного потока GUI. Пробывал различные ухищрения winAPIМетод... к сожалению FromHandle() всегда возвращает null Код ниже:

    namespace winForm
    {
       public partial class Form1 : Form
        {
           informer inf = new informer();
         
            public Form1()
            {
                InitializeComponent();
                inf.EventRaised += inf_EventRaised;
                inf.Start();
             
            }

            void inf_EventRaised(object sender, EventArgs e)
            {
                inf.Stop();
               var windowhandle = GetForegroundWindow();
               
                var currentControlHandle = GetFocusedHandleFromProcessWithWindow(windowhandle);
                var currentControl = Control.FromHandle(currentControlHandle);
               
                if (currentControl == null)
                     return;

            }

          
            [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern IntPtr GetFocus();
            [DllImport("user32.dll")]
            internal static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
            [DllImport("user32.dll",CharSet=CharSet.Auto, SetLastError = true)]
            internal static extern bool GetGUIThreadInfo(uint idThread, out GuiThreadInfo lpgui);
            [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern IntPtr GetForegroundWindow();

            IntPtr GetFocusedHandleFromProcessWithWindow(IntPtr window)
            {
                var threadId = GetWindowThreadProcessId(window, IntPtr.Zero);
                var info = new GuiThreadInfo();
                info.cbSize = (uint)Marshal.SizeOf(info);
             bool thinf =    GetGUIThreadInfo(0, out info);
                int LastErr = Marshal.GetLastWin32Error();
                    if(!thinf)
                    throw new Win32Exception();

                return info.hwndFocus;
            }

            [StructLayout(LayoutKind.Sequential)]
            internal struct GuiThreadInfo
            {
                public uint cbSize;
                public uint flags;
                public IntPtr hwndActive;
                public IntPtr hwndFocus;
                public IntPtr hwndCapture;
                public IntPtr hwndMenuOwner;
                public IntPtr hwndMoveSize;
                public IntPtr hwndCaret;
                public Rect rcCaret;
            }
            [StructLayout(LayoutKind.Sequential)]
            internal struct Rect
            {
                public uint Left;
                public uint Top;
                public uint Right;
                public uint Bottom;
            }

        }
               
          
       public class informer
       {
          System.Timers.Timer t;

          public event EventHandler EventRaised;
           public informer()
           {
               t = new System.Timers.Timer();
           }
           public void Start()
           {
               Thread timerThread = new Thread(new ThreadStart(Work));
               timerThread.Name = "TimerThread";
               timerThread.Start();
           }
           public void Stop()
           {
               if (t.Enabled)
                   t.Stop();
           }
            void Work()
           {
               t.Elapsed += t_Elapsed;
               t.Interval = 5000;
               t.Start();
               
              
           }

            void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                OnEventRaised(new EventArgs());
            }
           void OnEventRaised(EventArgs e)
           {
               if (EventRaised != null)
                   EventRaised(this, e);
           }


    17 июня 2014 г. 10:28

Все ответы