public void Show(Int32Rect rpRect)
        {
            var rMainWindowHandle = new WindowInteropHelper(App.Current.MainWindow).Handle;

            if (r_HwndSource == null)
            {
                var rParam = new HwndSourceParameters(nameof(ScreenshotToolOverlayWindow))
                {
                    Width = 0,
                    Height = 0,
                    PositionX = 0,
                    PositionY = 0,
                    WindowStyle = 0,
                    UsesPerPixelOpacity = true,
                    HwndSourceHook = WndProc,
                    ParentWindow = rMainWindowHandle,
                };

                r_HwndSource = new HwndSource(rParam) { SizeToContent = SizeToContent.Manual, RootVisual = this };
            }

            var rBrowserWindowHandle = ServiceManager.GetService<IBrowserService>().Handle;

            NativeStructs.RECT rBrowserWindowRect;
            NativeMethods.User32.GetWindowRect(rBrowserWindowHandle, out rBrowserWindowRect);

            var rHorizontalRatio = rBrowserWindowRect.Width / GameConstants.GameWidth;
            var rVerticalRatio = rBrowserWindowRect.Height / GameConstants.GameHeight;
            rpRect.X = (int)(rpRect.X * rHorizontalRatio);
            rpRect.Y = (int)(rpRect.Y * rVerticalRatio);
            rpRect.Width = (int)(rpRect.Width * rHorizontalRatio);
            rpRect.Height = (int)(rpRect.Height * rVerticalRatio);

            NativeMethods.User32.SetWindowPos(r_HwndSource.Handle, IntPtr.Zero, rBrowserWindowRect.Left + rpRect.X, rBrowserWindowRect.Top + rpRect.Y, rpRect.Width, rpRect.Height, NativeEnums.SetWindowPosition.SWP_NOZORDER | NativeEnums.SetWindowPosition.SWP_NOACTIVATE | NativeEnums.SetWindowPosition.SWP_SHOWWINDOW);
        }
Пример #2
0
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            var mode = e.Args.Any() ? e.Args[0] : "/s";

            // Preview mode--display in little window in Screen Saver dialog
            // (Not invoked with Preview button, which runs Screen Saver in
            // normal /s mode).
            if (mode.ToLower().StartsWith("/p"))
            {
                m_winSaver = new MainWindow();

                Int32 previewHandle = Convert.ToInt32(e.Args[1]);
                //WindowInteropHelper interopWin1 = new WindowInteropHelper(win);
                //interopWin1.Owner = new IntPtr(previewHandle);

                var pPreviewHnd = new IntPtr(previewHandle);

                var lpRect = new RECT();
                Win32API.GetClientRect(pPreviewHnd, ref lpRect);

                var sourceParams = new HwndSourceParameters("sourceParams")
                {
                    PositionX = 0,
                    PositionY = 0,
                    Height = lpRect.Bottom - lpRect.Top,
                    Width = lpRect.Right - lpRect.Left,
                    ParentWindow = pPreviewHnd,
                    WindowStyle = (int)(WindowStyles.WS_VISIBLE | WindowStyles.WS_CHILD | WindowStyles.WS_CLIPCHILDREN)
                };

                m_winWpfContent = new HwndSource(sourceParams);
                m_winWpfContent.Disposed += winWPFContent_Disposed;
                m_winWpfContent.RootVisual = m_winSaver.Grid;
                // ReSharper disable once CSharpWarnings::CS4014
                m_winSaver.StartAnimation();
            }

            // Normal screensaver mode.  Either screen saver kicked in normally,
            // or was launched from Preview button
            else if (mode.ToLower().StartsWith("/s"))
            {
                var win = new MainWindow { WindowState = WindowState.Maximized };
                win.Show();
            }

            // Config mode, launched from Settings button in screen saver dialog
            else if (mode.ToLower().StartsWith("/c"))
            {
                var win = new SettingsWindow();
                win.Show();
            }

            // If not running in one of the sanctioned modes, shut down the app
            // immediately (because we don't have a GUI).
            else
            {
                Current.Shutdown();
            }
        }
Пример #3
0
 public MessageWindow()
 {
     HwndSourceParameters sourceParams = new HwndSourceParameters()
     {
         ParentWindow = HWND_MESSAGE
     };
     Source = new HwndSource(sourceParams);
     Handle = Source.Handle;
 }
Пример #4
0
        public override void Show()
        {
            var parameters = new HwndSourceParameters(this.Name)
            {
                Width = 1,
                Height = 1,
                WindowStyle = 0x800000,
            };

            this.Show(parameters);
        }
Пример #5
0
        public override void Show()
        {
            var parameters = new HwndSourceParameters(ProductInfo.Title)
            {
                Width = 1,
                Height = 1,
                WindowStyle = (int)WS.BORDER,
            };

            this.Show(parameters);
        }
Пример #6
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var controller = new MainController();

            // Preview mode--display in little window in Screen Saver dialog
            // (Not invoked with Preview button, which runs Screen Saver in
            // normal /s mode).
            var argSwitch = e.Args[0].ToLower();
            if (argSwitch.StartsWith("/p"))
            {
                this.winSaver = new MainWindow(controller);

                var previewHandle = Convert.ToInt32(e.Args[1]);

                var previewHnd = new IntPtr(previewHandle);

                var rect = new RECT();
                Win32API.GetClientRect(previewHnd, ref rect);

                var sourceParams = new HwndSourceParameters("sourceParams")
                    {
                        PositionX = 0,
                        PositionY = 0,
                        Height = rect.Bottom - rect.Top,
                        Width = rect.Right - rect.Left,
                        ParentWindow = previewHnd,
                        WindowStyle =
                            (int)(WindowStyles.WS_VISIBLE | WindowStyles.WS_CHILD | WindowStyles.WS_CLIPCHILDREN)
                    };

                this.winWpfContent = new HwndSource(sourceParams);
                this.winWpfContent.Disposed += this.winWPFContent_Disposed;
                this.winWpfContent.RootVisual = this.winSaver.Content as Visual;
            }
            else if (argSwitch.StartsWith("/s"))
            {
                // Normal screensaver mode.  Either screen saver kicked in normally,
                // or was launched from Preview button
                var win = new MainWindow(controller) { WindowState = WindowState.Maximized };
                win.Show();
            }
            else if (argSwitch.StartsWith("/c"))
            {
                controller.ShowSettings.Execute(null);
            }
            else
            {
                // If not running in one of the sanctioned modes, shut down the app
                // immediately (because we don't have a GUI).
                Current.Shutdown();
            }
        }
Пример #7
0
        internal static void CreateHostHwnd(IntPtr parentHwnd)
        {
            // Set up the parameters for the host hwnd.
            HwndSourceParameters parameters = new HwndSourceParameters("Visual Hit Test", _width, _height);
            parameters.WindowStyle = WS_VISIBLE | WS_CHILD;
            parameters.SetPosition(0, 24);
            parameters.ParentWindow = parentHwnd;
            parameters.HwndSourceHook = new HwndSourceHook(ApplicationMessageFilter);

            // Create the host hwnd for the visuals.
            myHwndSource = new HwndSource(parameters);

            // Set the hwnd background color to the form's background color.
            myHwndSource.CompositionTarget.BackgroundColor = System.Windows.Media.Brushes.OldLace.Color;
        }
Пример #8
0
        protected override HandleRef BuildWindowCore(HandleRef hwndParent)
        {
            var param = new HwndSourceParameters("GeminiClippingHwndHost", (int) Width, (int) Height)
            {
                ParentWindow = hwndParent.Handle,
                WindowStyle = NativeMethods.WS_VISIBLE | NativeMethods.WS_CHILD,
            };

            _source = new HwndSource(param)
            {
                RootVisual = Content
            };

            return new HandleRef(null, _source.Handle);
        }
Пример #9
0
        internal static void CreateHostHwnd(IntPtr parentHwnd)
        {
            // Set up the parameters for the host hwnd.
            var parameters = new HwndSourceParameters("Visual Hit Test", Width, Height)
            {
                WindowStyle = WsVisible | WsChild
            };
            parameters.SetPosition(0, 24);
            parameters.ParentWindow = parentHwnd;
            parameters.HwndSourceHook = ApplicationMessageFilter;

            // Create the host hwnd for the visuals.
            MyHwndSource = new HwndSource(parameters);

            // Set the hwnd background color to the form's background color.
            MyHwndSource.CompositionTarget.BackgroundColor = Brushes.OldLace.Color;
        }
        public BrowserWrapper(string rpUri)
        {
            r_BrowserProviders = new List<IBrowserProvider>();
            var rBrowserPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Browsers");
            foreach (var rBrowser in Directory.EnumerateFiles(rBrowserPath, "*.dll"))
            {
                FileSystem.Unblock(rBrowser);

                var rAssembly = Assembly.LoadFile(rBrowser);
                var rTypes = rAssembly.GetTypes().Where(r => r.GetInterface(typeof(IBrowserProvider).FullName) != null);
                foreach (var rType in rTypes)
                {
                    r_BrowserProviders.Add((IBrowserProvider)rAssembly.CreateInstance(rType.FullName));
                }
            }

            BridgeReady = new ManualResetEventSlim(false);

            InitializeComponent();

            r_Uri = rpUri;
            r_Zoom = 1.0;

            Bridge = new Bridge<IBrowserWrapper, IBrowserHost>(this, r_Uri + "Browser", "Browser");
            Bridge.Connect(r_Uri + "BrowserHost");
            BridgeReady.Set();

            r_BrowserProvider = r_BrowserProviders.First();
            Container.Content = Browser = r_BrowserProvider.GetBrowser();

            var rParameters = new HwndSourceParameters(string.Format("Dentan.Browser({0})", r_BrowserProvider.BrowserName)) { WindowStyle = 0 };
            r_HwndSource = new HwndSource(rParameters) { SizeToContent = SizeToContent.Manual };
            r_HwndSource.CompositionTarget.BackgroundColor = Color.FromRgb(0x59, 0x59, 0x59);

            NativeMethods.User32.SetWindowLongPtr(r_HwndSource.Handle, NativeConstants.GetWindowLong.GWL_STYLE,
                (IntPtr)(NativeEnums.WindowStyle.WS_CHILD | NativeEnums.WindowStyle.WS_CLIPCHILDREN));
            NativeMethods.User32.SetWindowPos(r_HwndSource.Handle, IntPtr.Zero, 0, 0, 0, 0,
                NativeEnums.SetWindowPosition.SWP_FRAMECHANGED | NativeEnums.SetWindowPosition.SWP_NOMOVE | NativeEnums.SetWindowPosition.SWP_NOSIZE | NativeEnums.SetWindowPosition.SWP_NOZORDER);

            r_HwndSource.RootVisual = this;

            Bridge.Proxy.Attach(r_HwndSource.Handle);

            Browser.FlashExtracted += UpdateSize;
        }
Пример #11
0
        private void InitHwndSource()
        {
            var mousePos = Mouse.GetPosition(null);
            var activeScreen = Screen.FromPoint(new Point((int)mousePos.X, (int)mousePos.Y));
            var parameters = new HwndSourceParameters("SelectionShadow", activeScreen.Bounds.Width, activeScreen.Bounds.Height)
            {
                UsesPerPixelOpacity = true,
                PositionX = 0,
                PositionY = 0,
                WindowStyle = (int)(WS.POPUP | WS.VISIBLE | WS.CLIPCHILDREN | WS.CLIPSIBLINGS),
                ExtendedWindowStyle = (int)(WS_EX.TOPMOST | WS_EX.NOPARENTNOTIFY | WS_EX.TOOLWINDOW),
            };

            _hwndSource = new HwndSource(parameters)
            {
                RootVisual = InitRootVisual()
            };
        }
        protected override void Initialize()
        {
            if (_source == null)
            {
                ThrowIfNoControl();

                HwndSourceParameters p = new HwndSourceParameters();
                p.WindowStyle = (int)(WindowStyles.Child | WindowStyles.Visible | WindowStyles.ClipSiblings);
                p.ParentWindow = _parentHandle;
                p.Width = Math.Abs(_bounds.Left - _bounds.Right);
                p.Height = Math.Abs(_bounds.Top - _bounds.Bottom);

                _source = new HwndSource(p);
                _source.CompositionTarget.BackgroundColor = Brushes.WhiteSmoke.Color;
                _source.RootVisual = (Visual)Control.Content;
            }
            UpdatePlacement();
        }
 /// <summary>
 /// Compare two HwndSourceParameters blocks.
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public bool Equals(HwndSourceParameters obj)
 {
     return((this._classStyleBits == obj._classStyleBits) &&
            (this._styleBits == obj._styleBits) &&
            (this._extendedStyleBits == obj._extendedStyleBits) &&
            (this._x == obj._x) &&
            (this._y == obj._y) &&
            (this._width == obj._width) &&
            (this._height == obj._height) &&
            (this._name == obj._name) &&
            (this._parent == obj._parent) &&
            (this._hwndSourceHook == obj._hwndSourceHook) &&
            (this._adjustSizingForNonClientArea == obj._adjustSizingForNonClientArea) &&
            (this._hasAssignedSize == obj._hasAssignedSize)
            // && (this._colorKey == obj._colorKey)
            // && (this._opacity == obj._opacity)
            // && (this._opacitySpecified == obj._opacitySpecified)
            && (this._usesPerPixelOpacity == obj._usesPerPixelOpacity)
            );
 }
Пример #14
0
        /// <summary>
        /// Open the screensaver in the preview window of the screensaver settings of Windows.
        /// </summary>
        /// <param name="previewWndHandle">The handle of the parent window for the preview.</param>
        public MainWindow(IntPtr previewWndHandle)
            : this()
        {
            System.Drawing.Rectangle parentRect;
            User32.GetClientRect(previewWndHandle, out parentRect);

            //MessageBox.Show(parentRect.ToString());

            HwndSourceParameters sourceParams = new HwndSourceParameters();
            sourceParams.PositionX = 0;
            sourceParams.PositionY = 0;
            sourceParams.Height = parentRect.Height;
            sourceParams.Width = parentRect.Width;
            sourceParams.ParentWindow = previewWndHandle;
            sourceParams.WindowStyle = (int)(WindowStyles.WS_VISIBLE | WindowStyles.WS_CHILD | WindowStyles.WS_CLIPCHILDREN);

            HwndSource winWPFContent = new HwndSource(sourceParams);
            winWPFContent.Disposed += new EventHandler(winWPFContent_Disposed);
            winWPFContent.RootVisual = grid;

            Loaded += PreviewModeWindow_Loaded;

            shaderControl.InitializeFragmentShader();
        }
Пример #15
0
        public void Setup()
        {
            ITaskbarHelper helper = ServiceLocator.GetTaskbarHelper();

            Rectangle rectIcon = CalculateIconRectFromReBar(helper.TaskBarPosition.IsVertical(), helper.ReBarRect, _desiredOffset);
            Rectangle rectReBar = CalculateRebarRectWithIcon(helper.TaskBarPosition.IsVertical(), helper.ReBarRect, rectIcon);

            var hwndSourceParams = new HwndSourceParameters(WindowName, rectIcon.Width, rectIcon.Height);
            hwndSourceParams.PositionX = rectIcon.X;
            hwndSourceParams.PositionY = rectIcon.Y;

            // 94000C00 is from the Start button
            hwndSourceParams.WindowStyle = 0
                | (int)WindowsStyleConstants.WS_VISIBLE			        // 10000000
                | (int)WindowsStyleConstants.WS_CLIPSIBLINGS            // 04000000
                | (int)WindowsStyleConstants.RBS_BANDBORDERS            // 00000400
                | (int)WindowsStyleConstants.RBS_FIXEDORDER             // 00000800
            ;

            hwndSourceParams.ExtendedWindowStyle = 0
                | (int)ExtendedWindowsStyleConstants.WS_EX_TOOLWINDOW   //0x00000080
                | (int)ExtendedWindowsStyleConstants.WS_EX_LAYERED      //0x00080000
                | (int)ExtendedWindowsStyleConstants.WS_EX_TOPMOST      //0x00000008
            ;

            hwndSourceParams.UsesPerPixelOpacity = true;

            _hwndSource = new HwndSource(hwndSourceParams);
            _hwndSource.AddHook(TaskBarIconHookProc);
            _hwndSource.RootVisual = _control;

            var dll = ServiceLocator.GetNativeDll(NativeDllPath);
            dll.SetupSubclass(_hwndSource.Handle);

            UpdateReBarPosition(helper.ReBarHwnd, helper.ScreenToClient(helper.TaskBarHwnd, rectReBar));
            _taskBarControl.SetAllowedSize(rectIcon.Width, rectIcon.Height);
            UpdateReBarOffset(helper.ReBarHwnd, _desiredOffset);
        }
        protected override sealed HWND BuildWindowCore(HWND hwndParent)
        {
            HwndSourceParameters hwndSourceParameters = new HwndSourceParameters();
            hwndSourceParameters.WindowStyle = (int)(WS.VISIBLE | WS.CHILD | WS.CLIPSIBLINGS | WS.CLIPCHILDREN);
            //hwndSourceParameters.ExtendedWindowStyle = (int)(WS_EX.NOACTIVATE);
            hwndSourceParameters.ParentWindow = hwndParent.DangerousGetHandle();

            _hwndSource = new HwndSource(hwndSourceParameters);
            _hwndSource.SizeToContent = SizeToContent.Manual;

            // TODO: make this an option
            // On Vista, or when Win7 uses vista-blit, DX content is not
            // available via BitBlit or PrintWindow?  If WPF is using hardware
            // acceleration, anything it renders won't be available either.
            // One workaround is to force WPF to use software rendering.  Of
            // course, this is only a partial workaround since other content
            // like XNA or D2D won't work either.
            //_hwndSource.CompositionTarget.RenderMode = RenderMode.SoftwareOnly;

            // Set the root visual of the HwndSource to an instance of
            // HwndSourceHostRoot.  Hook it up as a logical child if
            // we are on the same thread.
            HwndSourceHostRoot root = new HwndSourceHostRoot();
            _hwndSource.RootVisual = root;

            root.OnMeasure += OnRootMeasured;
            AddLogicalChild(_hwndSource.RootVisual);

            SetRootVisual(Child);

            return new HWND(_hwndSource.Handle);
        }
 public HwndSource(HwndSourceParameters parameters)
 {
 }
 /// <summary>
 /// Compare two HwndSourceParameters blocks.
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public bool Equals(HwndSourceParameters obj)
 {
     return ((this._classStyleBits    == obj._classStyleBits)
          && (this._styleBits         == obj._styleBits)
          && (this._extendedStyleBits == obj._extendedStyleBits)
          && (this._x == obj._x)
          && (this._y == obj._y)
          && (this._width  == obj._width)
          && (this._height == obj._height)
          && (this._name   == obj._name)
          && (this._parent == obj._parent)
          && (this._hwndSourceHook  == obj._hwndSourceHook)
          && (this._adjustSizingForNonClientArea == obj._adjustSizingForNonClientArea)
          && (this._hasAssignedSize == obj._hasAssignedSize)
          // && (this._colorKey == obj._colorKey)
          // && (this._opacity == obj._opacity)
          // && (this._opacitySpecified == obj._opacitySpecified)
          && (this._usesPerPixelOpacity == obj._usesPerPixelOpacity)
           );
 }
Пример #19
0
 internal virtual HwndSourceParameters CreateHwndSourceParameters()
 {
     HwndSourceParameters param = new HwndSourceParameters(Title, NativeMethods.CW_USEDEFAULT, NativeMethods.CW_USEDEFAULT);
     param.UsesPerPixelOpacity = AllowsTransparency;
     param.WindowStyle = _Style;
     param.ExtendedWindowStyle = _StyleEx;
     param.ParentWindow = _ownerHandle;
     param.AdjustSizingForNonClientArea = true;
     param.HwndSourceHook = new HwndSourceHook(WindowFilterMessage); // hook to process window messages
     return param;
 }
Пример #20
0
        private HotkeyManager()
        {
            _keyBindings = new WeakReferenceCollection<KeyBinding>();

            var parameters = new HwndSourceParameters("Hotkey sink")
                             {
                                 HwndSourceHook = HandleMessage,
                                 ParentWindow = HwndMessage
                             };
            _source = new HwndSource(parameters);
            SetHwnd(_source.Handle);
        }
Пример #21
0
        public HwndSource(int classStyle,
                          int style,
                          int exStyle,
                          int x,
                          int y,
                          int width,
                          int height,
                          string name,
                          IntPtr parent,
                          bool adjustSizingForNonClientArea)
        {
            SecurityHelper.DemandUIWindowPermission();

            HwndSourceParameters parameters = new HwndSourceParameters(name, width, height);
            parameters.WindowClassStyle = classStyle;
            parameters.WindowStyle = style;
            parameters.ExtendedWindowStyle = exStyle;
            parameters.SetPosition(x, y);
            parameters.ParentWindow = parent;
            parameters.AdjustSizingForNonClientArea = adjustSizingForNonClientArea;
            Initialize(parameters);
        }
Пример #22
0
 public IntPtr Create(int classStyle, int style, int exStyle, int x, int y, int width, int height,
     string name, IntPtr parent)
 {
     HwndSourceParameters parameters = new HwndSourceParameters(name, width, height);
     parameters.WindowClassStyle = classStyle;
     parameters.WindowStyle = style;
     parameters.ExtendedWindowStyle = exStyle;
     parameters.SetPosition(x, y);
     parameters.ParentWindow = parent;
     parameters.HwndSourceHook = HwndSourceHook;
     return Create(parameters);
 }
Пример #23
0
 private IntPtr Create(HwndSourceParameters parameters)
 {
     DisposeHWndSource();
     _hwndSource = new HwndSource(parameters);
     _hwndSource.RootVisual = _decorator;
     (_hwndSource as IKeyboardInputSink).KeyboardInputSite = (ElementContainerInternal as IKeyboardInputSite);
     return _hwndSource.Handle;
 }
Пример #24
0
        public HwndSource(
            int classStyle,
            int style,
            int exStyle,
            int x,
            int y,
            string name,
            IntPtr parent)
        {
            SecurityHelper.DemandUIWindowPermission();

            HwndSourceParameters param = new HwndSourceParameters(name);
            param.WindowClassStyle = classStyle;
            param.WindowStyle = style;
            param.ExtendedWindowStyle = exStyle;
            param.SetPosition(x, y);
            param.ParentWindow = parent;
            Initialize(param);
        }
Пример #25
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            string[] args = e.Args;
            if (args.Length > 0)
            {
                // Get the 2 character command line argument
                string arg = args[0].ToLower(CultureInfo.InvariantCulture).Trim().Substring(0, 2);
                switch (arg)
                {
                    case "/o":
                        //Show the screensaver picking dialog
                        System.Diagnostics.Process.Start("control.exe", "desk.cpl,screensaver,@screensaver");
                        this.Shutdown();
                        break;
                    case "/c":
                        // Show the options dialog
                        Settings settings = new Settings();
                        settings.Show();
                        break;
                    case "/p":
                            //Show a preview
                            winPreview = new Main(1);

                            //A handle to the preview window is passed in
                            Int32 previewHandle = Convert.ToInt32(args[1]);

                            IntPtr pPreviewHnd = new IntPtr(previewHandle);

                            //Use the RECT struct & user32 dll to learn the size of the preview window
                            RECT lpRect = new RECT();
                            bool bGetRect = GetClientRect(pPreviewHnd, ref lpRect);

                            //Make our window fit in it
                            HwndSourceParameters sourceParams = new HwndSourceParameters("sourceParams");
                            sourceParams.PositionX = 0;
                            sourceParams.PositionY = 0;
                            sourceParams.Height = lpRect.Bottom - lpRect.Top;
                            sourceParams.Width = lpRect.Right - lpRect.Left;
                            sourceParams.ParentWindow = pPreviewHnd;

                            //WindowStyles.WS_VISIBLE | WindowStyles.WS_CHILD | WindowStyles.WS_CLIPCHILDREN
                            sourceParams.WindowStyle = (int)(0x52000000);

                            //Start to bind them together
                            winWPFContent = new HwndSource(sourceParams);
                            winWPFContent.Disposed += new EventHandler(winWPFContent_Disposed); //Makes sure the preview window exits!!!

                            //For now, we hide elements that don't scale correctly
                            //Later, the mainGrid will be able to handle all this for us
                            winPreview.lblAuthor.Height = 0;
                            winPreview.lblFeed.Height = 0;
                            winPreview.lblTitle.Height = 0;
                            winPreview.imgCore.Margin = new Thickness(1);

                            //Go!
                            winWPFContent.RootVisual = winPreview.mainGrid;
                        break;
                    case "/s":
                        // Show screensaver form
                        ShowScreensaver();
                        break;
                    default:
                        System.Windows.Application.Current.Shutdown();
                        break;
                }
            }
            else
            {
                // If no arguments were passed in, show the screensaver
                ShowScreensaver();
            }
        }
        /// <summary>
        /// Show our Preview user control in the little window provided by the Screen Saver control panel.
        /// </summary>
        /// <param name="hWnd">The hWnd passed to us by the Screen Saver control panel.</param>
        private void ShowPreview(IntPtr hWnd)
        {
            Log("ShowPreview(): Entered.");
            Log("   ShowPreview(): cpl hWnd passed to us = " + hWnd);

            if (NativeMethods.IsWindow(hWnd))
            {
                // Get the rect of the desired parent
                int error = 0;
                System.Drawing.Rectangle ParentRect = new System.Drawing.Rectangle();
                NativeMethods.SetLastErrorEx(0, 0);
                Log("  ShowPreview(): Let's Get the ClientRect of that puppy:");
                Log("  ShowPreview(): Calling GetClientRect(" + hWnd + ")...");
                bool fSuccess = NativeMethods.GetClientRect(hWnd, ref ParentRect);
                error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                Log("  ShowPreview(): GetClientRect() returned bool = " + fSuccess + ", rect = " + ParentRect.ToString());
                Log("      GetLastError() returned: " + error.ToString());
                Log(" ");

                // Create the HwndSource which will host our Preview user control
                Log("  ShowPreview(): Let's build a new HwndSource (src), and attach it to the cpl window:");
                HwndSourceParameters parameters = new HwndSourceParameters();
                parameters.WindowStyle = NativeMethods.WindowStyles.WS_CHILD | NativeMethods.WindowStyles.WS_VISIBLE;
                parameters.SetPosition(0, 0);  // in theory, our child will use values relative to parents position
                parameters.SetSize(ParentRect.Width, ParentRect.Height);
                parameters.ParentWindow = hWnd;
                HwndSource src = new HwndSource(parameters);

            #if DEBUG
                // Let's see what Windows thinks
                Log("  ShowPreview(): Attached it. Let's see what Windows thinks:");
                Log("  ShowPreview(): Calling GetParent(src.Handle)...");
                NativeMethods.SetLastErrorEx(0, 0);
                IntPtr handle = IntPtr.Zero;
                handle = NativeMethods.GetParent(src.Handle);
                error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                Log("  ShowPreview(): GetParent() returned: " + handle.ToString());
                Log("      GetLastError() returned: " + error.ToString());
                Log(" ");
            #endif

                // Create the user control and attach it
                Log("  ShowPreview(): Creating the user control (Preview)");
                PreviewControl Preview = new PreviewControl();
                Log("  ShowPreview(): setting src.RootVisual to user control...");
                src.RootVisual = Preview;
                Preview.Visibility = Visibility.Visible;

            #if DEBUG
                // Let's find out what Windows thinks
                Log("  ShowPreview(): Set it. Let's see what Windows thinks the HwndSource for Preview is:");
                HwndSource hs = (HwndSource)HwndSource.FromVisual(Preview);
                Log("  ShowPreview(): HwndSource.FromVisual(Preview) is: " + HwndSource.FromVisual(Preview));
                Log("  ShowPreview(): Let's see what Windows thinks the parent hWnd of Preview is:");
                Log("  ShowPreview(): Calling GetParent((HwndSource)HwndSource.FromVisual(Preview).handle)...");
                NativeMethods.SetLastErrorEx(0, 0);
                IntPtr ucHandle = IntPtr.Zero;
                handle = NativeMethods.GetParent(hs.Handle);
                error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                Log("  ShowPreview(): GetParent() returned: " + handle.ToString());
                Log("      GetLastError() returned: " + error.ToString());
                Log(" ");

                Log("  ShowPreview(): Is the src window visible?");
                Log("  ShowPreview(): Calling IsWindowVisible(src.Handle)...");
                NativeMethods.SetLastErrorEx(0, 0);
                bool fVisible = NativeMethods.IsWindowVisible(src.Handle);
                error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                Log("  ShowPreview(): IsWindowVisible() returned: " + fVisible.ToString());
                Log("      GetLastError() returned: " + error.ToString());
                Log(" ");
            #endif

                // Let's hook into src's message pump
                Log("  ShowPreview(): Let's hook into src's message pump");
                // TODO: determine if we need to hook into message pump

            }
            else
            {
                Log("  ShowPreview(): Invalid hWnd passed: " + hWnd.ToString());
                throw new ArgumentException("Invalid hWnd passed to ShowPreview(): " + hWnd.ToString());
            }

            Log("ShowPreview(): exiting.");
        }
Пример #27
0
        private void InitHwndSource()
        {
            if(m_hwndSource != null) return;

            int classStyle = 0;
            int style = 0;
            int styleEx = Win32.WS_EX_NOACTIVATE;

            HwndSourceParameters parameters = new HwndSourceParameters()
            {
                UsesPerPixelOpacity = true,
                WindowClassStyle = classStyle,
                WindowStyle = style,
                ExtendedWindowStyle = styleEx,
                PositionX = (int)(m_parentBoundingBox.X + m_boundingBox.X),
                PositionY = (int)(m_parentBoundingBox.Y + m_boundingBox.Y),
                Width = (int)(m_boundingBox.Width),
                Height = (int)(m_boundingBox.Height)
            };

            m_hwndSource = new HwndSource(parameters);
            m_hwndSource.RootVisual = m_hwndAdornmentRoot;
            m_hwndSource.AddHook(WndProc);

            m_shown = false;
        }
Пример #28
0
        /// <summary>
        /// Convert the framework element to a Window Handle so it can be serialized.
        /// </summary>
        /// <param name="frameworkElement">The framework element to convert to a Window Handle.</param>
        /// <returns>The Window Handle that is hosting the framework element.</returns>
        static long CreateWindowHandle(Visual frameworkElement)
        {
            // ReSharper disable InconsistentNaming
            const int WS_VISIBLE = 0x10000000;
            // ReSharper restore InconsistentNaming

            var parameters = new HwndSourceParameters(String.Format("NewWindowHost{0}", Guid.NewGuid()), 1, 1);
            parameters.WindowStyle &= ~WS_VISIBLE;

            var intPtr = new HwndSource(parameters)
            {
                RootVisual = frameworkElement
            }.Handle;
            return intPtr.ToInt64();
        }
Пример #29
0
 public HwndSource(HwndSourceParameters parameters)
 {
     Initialize(parameters);
 }
 public HwndSource(HwndSourceParameters parameters)
 {
 }
        protected override sealed HWND BuildWindowOverride(HWND hwndParent)
        {
            HwndSourceParameters hwndSourceParameters = new HwndSourceParameters();
            hwndSourceParameters.WindowStyle = (int)(WS.VISIBLE | WS.CHILD | WS.CLIPSIBLINGS | WS.CLIPCHILDREN);
            hwndSourceParameters.ParentWindow = hwndParent.DangerousGetHandle();

            _hwndSource = new HwndSource(hwndSourceParameters);
            _hwndSource.SizeToContent = SizeToContent.Manual;

            // Set the root visual of the HwndSource to an instance of
            // HwndSourceHostRoot.  Hook it up as a logical child if
            // we are on the same thread.
            HwndSourceHostRoot root = new HwndSourceHostRoot();
            _hwndSource.RootVisual = root;

            root.OnMeasure += OnRootMeasured;
            AddLogicalChild(_hwndSource.RootVisual);

            SetRootVisual(Child);

            return new HWND(_hwndSource.Handle);
        }
Пример #32
0
        private void Initialize(HwndSourceParameters parameters)
        {
            _mouse = new SecurityCriticalDataClass<HwndMouseInputProvider>(new HwndMouseInputProvider(this));
            _keyboard = new SecurityCriticalDataClass<HwndKeyboardInputProvider>(new HwndKeyboardInputProvider(this));
            _layoutHook = new HwndWrapperHook(LayoutFilterMessage);
            _inputHook = new HwndWrapperHook(InputFilterMessage);
            _hwndTargetHook = new HwndWrapperHook(HwndTargetFilterMessage);

            _publicHook = new HwndWrapperHook(PublicHooksFilterMessage);

            // When processing WM_SIZE, LayoutFilterMessage must be invoked before
            // HwndTargetFilterMessage. This way layout will be updated before resizing
            // HwndTarget, resulting in single render per resize. This means that
            // layout hook should appear before HwndTarget hook in the wrapper hooks
            // list. If this is done the other way around, first HwndTarget resize will
            // force re-render, then layout will be updated according to the new size,
            // scheduling another render.
            HwndWrapperHook[] wrapperHooks = { _hwndTargetHook, _layoutHook, _inputHook, null };

            if (null != parameters.HwndSourceHook)
            {
                // In case there's more than one delegate, add these to the event storage backwards
                // so they'll get invoked in the expected order.
                Delegate[] handlers = parameters.HwndSourceHook.GetInvocationList();
                for (int i = handlers.Length -1; i >= 0; --i)
                {
                    _hooks += (HwndSourceHook)handlers[i];
                }
                wrapperHooks[3] = _publicHook;
            }

            _restoreFocusMode = parameters.RestoreFocusMode;
            _acquireHwndFocusInMenuMode = parameters.AcquireHwndFocusInMenuMode;

            // A window must be marked WS_EX_LAYERED if (and only if):
            // 1) it is not a child window
            //    -- AND --
            // 2) a color-key is specified
            // 3) or an opacity other than 1.0 is specified
            // 4) or per-pixel alpha is requested.
            if((parameters.WindowStyle & NativeMethods.WS_CHILD) == 0 &&
               ( //parameters.ColorKey != null ||
                 //!MS.Internal.DoubleUtil.AreClose(parameters.Opacity, 1.0) ||
                parameters.UsesPerPixelOpacity))
            {
                parameters.ExtendedWindowStyle |= NativeMethods.WS_EX_LAYERED;
            }
            else
            {
                parameters.ExtendedWindowStyle &= (~NativeMethods.WS_EX_LAYERED);
            }


            _constructionParameters = parameters;
            _hwndWrapper = new HwndWrapper(parameters.WindowClassStyle,
                                       parameters.WindowStyle,
                                       parameters.ExtendedWindowStyle,
                                       parameters.PositionX,
                                       parameters.PositionY,
                                       parameters.Width,
                                       parameters.Height,
                                       parameters.WindowName,
                                       parameters.ParentWindow,
                                       wrapperHooks);

            _hwndTarget = new HwndTarget(_hwndWrapper.Handle);
            //_hwndTarget.ColorKey = parameters.ColorKey;
            //_hwndTarget.Opacity = parameters.Opacity;
            _hwndTarget.UsesPerPixelOpacity = parameters.UsesPerPixelOpacity;
            if(_hwndTarget.UsesPerPixelOpacity)
            {
                _hwndTarget.BackgroundColor = Colors.Transparent;

                // Prevent this window from being themed.
                UnsafeNativeMethods.CriticalSetWindowTheme(new HandleRef(this, _hwndWrapper.Handle), "", "");
            }
            _constructionParameters = null;

            if (!parameters.HasAssignedSize)
                _sizeToContent = SizeToContent.WidthAndHeight;

            _adjustSizingForNonClientArea = parameters.AdjustSizingForNonClientArea;
            _treatAncestorsAsNonClientArea = parameters.TreatAncestorsAsNonClientArea;
            
            // Listen to the UIContext.Disposed event so we can clean up.
            // The HwndTarget cannot work without a MediaContext which
            // is disposed when the UIContext is disposed.  So we need to
            // dispose the HwndTarget and also never use it again (to
            // paint or process input).  The easiest way to do this is to just
            // dispose the HwndSource at the same time.
            _weakShutdownHandler = new WeakEventDispatcherShutdown(this, this.Dispatcher);

            // Listen to the HwndWrapper.Disposed event so we can clean up.
            // The HwndTarget cannot work without a live HWND, and since
            // the HwndSource represents an HWND, we make sure we dispose
            // ourselves if the HWND is destroyed out from underneath us.
            _hwndWrapper.Disposed += new EventHandler(OnHwndDisposed);

            _stylus = new SecurityCriticalDataClass<HwndStylusInputProvider>(new HwndStylusInputProvider(this));

            // WM_APPCOMMAND events are handled thru this.
            _appCommand = new SecurityCriticalDataClass<HwndAppCommandInputProvider>(new HwndAppCommandInputProvider(this));

            // Register the top level source with the ComponentDispatcher.
            if (parameters.TreatAsInputRoot)
            {
                _weakPreprocessMessageHandler = new WeakEventPreprocessMessage(this, false);
            }
            AddSource();

            // Register dropable window.
            // The checking CallerHasPermissionWithAppDomainOptimization will call RegisterDropTarget
            // safely without the security exception in case of no unmanaged code permission.
            // So RegisterDropTarget will be called safely in case of having the unmanged code permission.
            // Otherwise, the security exception cause System.Printing to be instatiated which will
            // load system.drawing module.
            if (_hwndWrapper.Handle != IntPtr.Zero &&
                SecurityHelper.CallerHasPermissionWithAppDomainOptimization(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)))
            {
                // This call is safe since DragDrop.RegisterDropTarget is checking the unmanged
                // code permission.
                DragDrop.RegisterDropTarget(_hwndWrapper.Handle);
                _registeredDropTargetCount++;
            }
        }