WPF中获取Hwnd与窗体,Uid获取控件


void MapControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.OnApplyTemplate();
            CurrentMapChanged(new DependencyPropertyChangedEventArgs(MapControl.PropertyCurrentMap, "", ""));

            //
            Window parentWindow = Window.GetWindow(this);
            IntPtr handle = (new WindowInteropHelper(parentWindow)).Handle;
            Console.WriteLine("parentWindow WHnd: " + handle.ToInt32());

            HwndSource hwndSource = HwndSource.FromHwnd(handle);
            Visual visual = hwndSource.RootVisual;

            Window window = (Window)visual;
            Console.WriteLine("parentWindow WHnd: " + window.Title);
            //
            String mapUid = Guid.NewGuid().ToString();
            this.Uid = mapUid;
            //
            Console.WriteLine("this control uid: " + this.Uid);
            UIElement elem = this.FindUIElementByUid(window, mapUid);
            if(elem != null)
            {
                Console.WriteLine("this control uid: " + elem.Uid);
            }
            

        }


        private UIElement FindUIElementByUid(DependencyObject parent, string uid)
        {
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                UIElement el = VisualTreeHelper.GetChild(parent, i) as UIElement;
                if (el == null) continue;
                Console.WriteLine("el.Uid: " + el.Uid);
                if (el.Uid == uid) { return el; }
                UIElement el1 = FindUIElementByUid(el, uid);
                if (el1 != null) { return el1; }
            }
            //
            if (parent is ContentControl)
            {
                UIElement content = (parent as ContentControl).Content as UIElement;
                if (content != null)
                {
                    Console.WriteLine("content.Uid: " + content.Uid);
                    if (content.Uid == uid) return content;
                    UIElement el1 = FindUIElementByUid(content, uid);
                    if (el1 != null) { return el1; }
                }
            }

            return null;
        }


-----------------------------------

你可能感兴趣的:(WPF中获取Hwnd与窗体,Uid获取控件)