WPF 使用SetParent嵌套窗口


有點類似與Winform的MDI窗口。

使用函數為SetParent和MoveWindow(經常配合)。

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

        [DllImport("user32.dll", EntryPoint = "SetParent")]
        public static extern int SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

 

給個小例子,例如嵌套TIM的聊天窗口

其中window1 就是新建的窗口 里面什么都沒有寫,默認

public partial class MainWindow : Window
    {
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

        [DllImport("user32.dll", EntryPoint = "SetParent")]
        public static extern int SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32", EntryPoint = "GetDesktopWindow")]
        public static extern IntPtr IntPtrGetDesktopWindow();

        public MainWindow()
        {
            InitializeComponent();
          
        }
        int baseSize =700;
        bool IsOpen = false;
        int Num = 1;
        Window1 window;
        private void MainWindow_Closed(object sender, EventArgs e)
        {
           // var childhwnd = FindWindow("TXGuiFoundation", "唐大人的 iPhone");
            var d = SetParent(childhwnd, IntPtrGetDesktopWindow());
            MoveWindow(childhwnd, 0, 0, baseSize + Num+10, baseSize + Num+10, true);
        }
        IntPtr childhwnd;
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            IntPtr hwnd = new WindowInteropHelper(window).Handle;
             childhwnd = FindWindow("TXGuiFoundation", "唐大人的 iPhone");
                //(IntPtr)Convert.ToInt32("000307BA", 16);
            var d = SetParent(childhwnd, hwnd);
            MoveWindow(childhwnd, 0, 0, 600, 600, true);
        }
       
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (!IsOpen)
            {
                window = new Window1();
                window.Loaded += MainWindow_Loaded;
                window.Closed += MainWindow_Closed;
                window.Show();
                IsOpen = true;
                Num++;
                return;
            }
            Num++;
            window.Close();
            IsOpen = false;
        }

        
    }

 

截圖

 

SetParent的問題:

1 使用API后,子窗口在父窗口中不顯示但是可以顯示鼠標的拖拉動作(窗口調整)

2 使用API后,子窗口在父窗口中不再具有焦點,也不可以點擊,看起來和圖片差不多

3 使用API后,子窗口在原桌面留下空白且可以在空白操控父窗口內的子窗口而在父窗口內則是不可以操作子窗口(針對firefox瀏覽器[官方發行版])

 

相對來說嵌套的問題不少,可以說有很多問題。 本文中的代碼是可以解決問題1(就是修改窗口的大小,嵌套時窗口大小要大於原先,釋放時也要大於嵌套時,如果對釋放和嵌套時對大小有要求可以多次修改窗口大小)。其他問題則是需要考慮windows消息機制(個人看法)了。

至於如何釋放子窗口則是將子窗口的父窗口重新設置回去就好了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM