天天看點

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消息機制(個人看法)了。

至于如何釋放子視窗則是将子視窗的父視窗重新設定回去就好了。