Exemple #1
0
        private void GetPlatformWindowSize(out int w, out int h)
        {
#if __IOS__
            var bounds = GetApplicationFrame();
            w = (int)bounds.Width;
            h = (int)bounds.Height;
#elif WIN32
            UnmanagedMethods.RECT rc;
            UnmanagedMethods.GetClientRect(_hwnd.Handle, out rc);
            w = rc.right - rc.left;
            h = rc.bottom - rc.top;
#elif __ANDROID__
            var surfaceView = _hwnd as SurfaceView;
            w = surfaceView.Width;
            h = surfaceView.Height;
#else
            throw new NotImplementedException();
#endif
        }
Exemple #2
0
        public WindowImpl()
        {
#if USE_MANAGED_DRAG
            _managedDrag = new ManagedWindowResizeDragHelper(this, capture =>
            {
                if (capture)
                {
                    UnmanagedMethods.SetCapture(Handle.Handle);
                }
                else
                {
                    UnmanagedMethods.ReleaseCapture();
                }
            });
#endif
            CreateWindow();
            _framebuffer = new FramebufferManager(_hwnd);
            s_instances.Add(this);
        }
        private Vector GetCurrentDpi()
        {
            if (UnmanagedMethods.ShCoreAvailable && Win32Platform.WindowsVersion > PlatformConstants.Windows8)
            {
                var monitor =
                    UnmanagedMethods.MonitorFromWindow(_hwnd, UnmanagedMethods.MONITOR.MONITOR_DEFAULTTONEAREST);

                if (UnmanagedMethods.GetDpiForMonitor(
                        monitor,
                        UnmanagedMethods.MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI,
                        out var dpix,
                        out var dpiy) == 0)
                {
                    return(new Vector(dpix, dpiy));
                }
            }

            return(new Vector(96, 96));
        }
Exemple #4
0
        protected override IntPtr CreateWindowOverride(ushort atom)
        {
            var hWnd = UnmanagedMethods.CreateWindowEx(
                0,
                atom,
                null,
                (int)UnmanagedMethods.WindowStyles.WS_CHILD,
                0,
                0,
                640,
                480,
                WinFormsControl.Handle,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero);

            Handle = hWnd;
            return(hWnd);
        }
Exemple #5
0
        public WicBitmapImpl(APixelFormat format, IntPtr data, PixelSize size, Vector dpi, int stride)
        {
            WicImpl = new Bitmap(Direct2D1Platform.ImagingFactory, size.Width, size.Height, format.ToWic(), BitmapCreateCacheOption.CacheOnDemand);
            WicImpl.SetResolution(dpi.X, dpi.Y);

            PixelFormat = format;
            Dpi         = dpi;

            using (var l = WicImpl.Lock(BitmapLockFlags.Write))
            {
                for (var row = 0; row < size.Height; row++)
                {
                    UnmanagedMethods.CopyMemory(
                        (l.Data.DataPointer + row * l.Stride),
                        (data + row * stride),
                        (UIntPtr)l.Data.Pitch);
                }
            }
        }
Exemple #6
0
        public WindowImpl()
        {
            _disabledBy  = new List <WindowImpl>();
            _touchDevice = new TouchDevice();
            _mouseDevice = new WindowsMouseDevice();

#if USE_MANAGED_DRAG
            _managedDrag = new ManagedWindowResizeDragHelper(this, capture =>
            {
                if (capture)
                {
                    UnmanagedMethods.SetCapture(Handle.Handle);
                }
                else
                {
                    UnmanagedMethods.ReleaseCapture();
                }
            });
#endif

            _windowProperties = new WindowProperties
            {
                ShowInTaskbar = false,
                IsResizable   = true,
                Decorations   = SystemDecorations.Full
            };
            _rendererLock = new ManagedDeferredRendererLock();


            CreateWindow();
            _framebuffer = new FramebufferManager(_hwnd);

            if (Win32GlManager.EglFeature != null)
            {
                _gl = new EglGlPlatformSurface((EglDisplay)Win32GlManager.EglFeature.Display,
                                               Win32GlManager.EglFeature.DeferredContext, this);
            }

            Screen = new ScreenImpl();

            s_instances.Add(this);
        }
Exemple #7
0
        private static IEnumerable <string> ReadFileNamesFromHGlobal(IntPtr hGlobal)
        {
            List <string> files     = new List <string>();
            int           fileCount = UnmanagedMethods.DragQueryFile(hGlobal, -1, null, 0);

            if (fileCount > 0)
            {
                for (int i = 0; i < fileCount; i++)
                {
                    int           pathLen = UnmanagedMethods.DragQueryFile(hGlobal, i, null, 0);
                    StringBuilder sb      = new StringBuilder(pathLen + 1);

                    if (UnmanagedMethods.DragQueryFile(hGlobal, i, sb, sb.Capacity) == pathLen)
                    {
                        files.Add(sb.ToString());
                    }
                }
            }
            return(files);
        }
Exemple #8
0
        public IDisposable StartTimer(DispatcherPriority priority, TimeSpan interval, Action callback)
        {
            UnmanagedMethods.TimerProc timerDelegate =
                (hWnd, uMsg, nIDEvent, dwTime) => callback();

            IntPtr handle = UnmanagedMethods.SetTimer(
                IntPtr.Zero,
                IntPtr.Zero,
                (uint)interval.TotalMilliseconds,
                timerDelegate);

            // Prevent timerDelegate being garbage collected.
            _delegates.Add(timerDelegate);

            return(Disposable.Create(() =>
            {
                _delegates.Remove(timerDelegate);
                UnmanagedMethods.KillTimer(IntPtr.Zero, handle);
            }));
        }
Exemple #9
0
        private int WriteFileListToHGlobal(ref IntPtr hGlobal, IEnumerable <string> files)
        {
            if (!files?.Any() ?? false)
            {
                return(unchecked ((int)UnmanagedMethods.HRESULT.S_OK));
            }

            char[]     filesStr = (string.Join("\0", files) + "\0\0").ToCharArray();
            _DROPFILES df       = new _DROPFILES();

            df.pFiles = Marshal.SizeOf <_DROPFILES>();
            df.fWide  = true;

            int required = (filesStr.Length * sizeof(char)) + Marshal.SizeOf <_DROPFILES>();

            if (hGlobal == IntPtr.Zero)
            {
                hGlobal = UnmanagedMethods.GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, required);
            }

            long available = UnmanagedMethods.GlobalSize(hGlobal).ToInt64();

            if (required > available)
            {
                return(STG_E_MEDIUMFULL);
            }

            IntPtr ptr = UnmanagedMethods.GlobalLock(hGlobal);

            try
            {
                Marshal.StructureToPtr(df, ptr, false);

                Marshal.Copy(filesStr, 0, ptr + Marshal.SizeOf <_DROPFILES>(), filesStr.Length);
                return(unchecked ((int)UnmanagedMethods.HRESULT.S_OK));
            }
            finally
            {
                UnmanagedMethods.GlobalUnlock(hGlobal);
            }
        }
Exemple #10
0
        public async Task SetTextAsync(string text)
        {
            if (text == null)
            {
                throw new ArgumentNullException(nameof(text));
            }

            await OpenClipboard();

            UnmanagedMethods.EmptyClipboard();

            try
            {
                var hGlobal = Marshal.StringToHGlobalUni(text);
                UnmanagedMethods.SetClipboardData(UnmanagedMethods.ClipboardFormat.CF_UNICODETEXT, hGlobal);
            }
            finally
            {
                UnmanagedMethods.CloseClipboard();
            }
        }
        public unsafe Task <DragDropEffects> DoDragDrop(PointerEventArgs triggerEvent,
                                                        IDataObject data, DragDropEffects allowedEffects)
        {
            Dispatcher.UIThread.VerifyAccess();

            triggerEvent.Pointer.Capture(null);

            using var dataObject = new DataObject(data);
            using var src        = new OleDragSource();
            var allowed = OleDropTarget.ConvertDropEffect(allowedEffects);

            var objPtr = MicroCom.MicroComRuntime.GetNativeIntPtr <Win32Com.IDataObject>(dataObject);
            var srcPtr = MicroCom.MicroComRuntime.GetNativeIntPtr <Win32Com.IDropSource>(src);

            UnmanagedMethods.DoDragDrop(objPtr, srcPtr, (int)allowed, out var finalEffect);

            // Force releasing of internal wrapper to avoid memory leak, if drop target keeps com reference.
            dataObject.ReleaseWrapped();

            return(Task.FromResult(OleDropTarget.ConvertDropEffect((Win32Com.DropEffect)finalEffect)));
        }
        private void Queue(DispatcherPriority priority, DispatcherOperation x)
        {
            int          p = (int)priority;
            PokableQueue q = this.priorityQueues[p];

            lock (q)
            {
                int flag = 1 << p;
                q.Enqueue(x);
                this.queueBits |= flag;
            }

            if (Thread.CurrentThread != this.baseThread)
            {
                UnmanagedMethods.PostMessage(
                    IntPtr.Zero,
                    (int)UnmanagedMethods.WindowsMessage.WM_DISPATCH_WORK_ITEM,
                    IntPtr.Zero,
                    IntPtr.Zero);
            }
        }
Exemple #13
0
        public static void Initialize(bool deferredRendering = true)
        {
            AvaloniaLocator.CurrentMutable
            .Bind <IClipboard>().ToSingleton <ClipboardImpl>()
            .Bind <IStandardCursorFactory>().ToConstant(CursorFactory.Instance)
            .Bind <IKeyboardDevice>().ToConstant(WindowsKeyboardDevice.Instance)
            .Bind <IPlatformSettings>().ToConstant(s_instance)
            .Bind <IPlatformThreadingInterface>().ToConstant(s_instance)
            .Bind <IRenderLoop>().ToConstant(new RenderLoop(60))
            .Bind <ISystemDialogImpl>().ToSingleton <SystemDialogImpl>()
            .Bind <IWindowingPlatform>().ToConstant(s_instance)
            .Bind <IPlatformIconLoader>().ToConstant(s_instance);

            if (OleContext.Current != null)
            {
                AvaloniaLocator.CurrentMutable.Bind <IPlatformDragSource>().ToSingleton <DragSource>();
            }

            UseDeferredRendering = deferredRendering;
            _uiThread            = UnmanagedMethods.GetCurrentThreadId();
        }
Exemple #14
0
        public async Task <string> GetTextAsync()
        {
            using (await OpenClipboard())
            {
                IntPtr hText = UnmanagedMethods.GetClipboardData(UnmanagedMethods.ClipboardFormat.CF_UNICODETEXT);
                if (hText == IntPtr.Zero)
                {
                    return(null);
                }

                var pText = UnmanagedMethods.GlobalLock(hText);
                if (pText == IntPtr.Zero)
                {
                    return(null);
                }

                var rv = Marshal.PtrToStringUni(pText);
                UnmanagedMethods.GlobalUnlock(hText);
                return(rv);
            }
        }
Exemple #15
0
        public bool DrawToWindow(IntPtr hWnd, int destX = 0, int destY = 0, int srcX = 0, int srcY = 0, int width = -1,
                                 int height             = -1)
        {
            if (_pBitmap == IntPtr.Zero)
            {
                throw new ObjectDisposedException("Framebuffer");
            }
            if (hWnd == IntPtr.Zero)
            {
                return(false);
            }
            IntPtr hDC = UnmanagedMethods.GetDC(hWnd);

            if (hDC == IntPtr.Zero)
            {
                return(false);
            }
            DrawToDevice(hDC, destX, destY, srcX, srcY, width, height);
            UnmanagedMethods.ReleaseDC(hWnd, hDC);
            return(true);
        }
Exemple #16
0
        public void CanResize(bool value)
        {
            if (value == _resizable)
            {
                return;
            }

            var style = (UnmanagedMethods.WindowStyles)UnmanagedMethods.GetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_STYLE);

            if (value)
            {
                style |= UnmanagedMethods.WindowStyles.WS_SIZEFRAME;
            }
            else
            {
                style &= ~(UnmanagedMethods.WindowStyles.WS_SIZEFRAME);
            }

            UnmanagedMethods.SetWindowLong(_hwnd, (int)UnmanagedMethods.WindowLongParam.GWL_STYLE, (uint)style);
            _resizable = value;
        }
Exemple #17
0
        private static IntPtr CreateParentWindow()
        {
            _wndProcDelegate = new UnmanagedMethods.WndProc(ParentWndProc);

            var wndClassEx = new UnmanagedMethods.WNDCLASSEX
            {
                cbSize        = Marshal.SizeOf <UnmanagedMethods.WNDCLASSEX>(),
                hInstance     = UnmanagedMethods.GetModuleHandle(null),
                lpfnWndProc   = _wndProcDelegate,
                lpszClassName = "AvaloniaEmbeddedWindow-" + Guid.NewGuid(),
            };

            var atom = UnmanagedMethods.RegisterClassEx(ref wndClassEx);

            if (atom == 0)
            {
                throw new Win32Exception();
            }

            var hwnd = UnmanagedMethods.CreateWindowEx(
                0,
                atom,
                null,
                (int)UnmanagedMethods.WindowStyles.WS_OVERLAPPEDWINDOW,
                UnmanagedMethods.CW_USEDEFAULT,
                UnmanagedMethods.CW_USEDEFAULT,
                UnmanagedMethods.CW_USEDEFAULT,
                UnmanagedMethods.CW_USEDEFAULT,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero);

            if (hwnd == IntPtr.Zero)
            {
                throw new Win32Exception();
            }

            return(hwnd);
        }
Exemple #18
0
        private Size GetWindowDpiWin32()
        {
            if (UnmanagedMethods.ShCoreAvailable)
            {
                uint dpix, dpiy;

                var monitor = UnmanagedMethods.MonitorFromWindow(
                    _hwnd.Handle,
                    UnmanagedMethods.MONITOR.MONITOR_DEFAULTTONEAREST);

                if (UnmanagedMethods.GetDpiForMonitor(
                        monitor,
                        UnmanagedMethods.MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI,
                        out dpix,
                        out dpiy) == 0)
                {
                    return(new Size(dpix, dpiy));
                }
            }

            return(new Size(96, 96));
        }
Exemple #19
0
        protected override Size2F GetWindowDpi()
        {
            if (UnmanagedMethods.ShCoreAvailable)
            {
                uint dpix, dpiy;

                var monitor = UnmanagedMethods.MonitorFromWindow(
                    _window.Handle,
                    UnmanagedMethods.MONITOR.MONITOR_DEFAULTTONEAREST);

                if (UnmanagedMethods.GetDpiForMonitor(
                        monitor,
                        UnmanagedMethods.MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI,
                        out dpix,
                        out dpiy) == 0)
                {
                    return(new Size2F(dpix, dpiy));
                }
            }

            return(new Size2F(96, 96));
        }
            public DumbWindow(bool layered = false, IntPtr?parent = null)
            {
                _wndProcDelegate = WndProc;
                var wndClassEx = new UnmanagedMethods.WNDCLASSEX
                {
                    cbSize        = Marshal.SizeOf <UnmanagedMethods.WNDCLASSEX>(),
                    hInstance     = UnmanagedMethods.GetModuleHandle(null),
                    lpfnWndProc   = _wndProcDelegate,
                    lpszClassName = _className = "AvaloniaDumbWindow-" + Guid.NewGuid(),
                };

                var atom = UnmanagedMethods.RegisterClassEx(ref wndClassEx);

                Handle = UnmanagedMethods.CreateWindowEx(
                    layered ? (int)UnmanagedMethods.WindowStyles.WS_EX_LAYERED : 0,
                    atom,
                    null,
                    (int)UnmanagedMethods.WindowStyles.WS_CHILD,
                    0,
                    0,
                    640,
                    480,
                    parent ?? OffscreenParentWindow.Handle,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    IntPtr.Zero);

                if (Handle == IntPtr.Zero)
                {
                    throw new InvalidOperationException("Unable to create child window for native control host. Application manifest with supported OS list might be required.");
                }

                if (layered)
                {
                    UnmanagedMethods.SetLayeredWindowAttributes(Handle, 0, 255,
                                                                UnmanagedMethods.LayeredWindowFlags.LWA_ALPHA);
                }
            }
Exemple #21
0
        private void ShowWindow(WindowState state)
        {
            UnmanagedMethods.ShowWindowCommand command;

            bool maximizeFillsDesktop = false; // otherwise we cover entire screen.

            switch (state)
            {
            case WindowState.Minimized:
                command = ShowWindowCommand.Minimize;
                break;

            case WindowState.Maximized:
                command = ShowWindowCommand.Maximize;

                if (!_decorated && !_coverTaskBarWhenMaximized)
                {
                    maximizeFillsDesktop = true;
                }
                break;

            case WindowState.Normal:
                command = ShowWindowCommand.Restore;
                break;

            default:
                throw new ArgumentException("Invalid WindowState.");
            }

            UnmanagedMethods.ShowWindow(_hwnd, command);

            if (maximizeFillsDesktop)
            {
                MaximizeWithoutCoveringTaskbar();
            }

            SetFocus(_hwnd);
        }
        public WindowImpl()
        {
#if USE_MANAGED_DRAG
            _managedDrag = new ManagedWindowResizeDragHelper(this, capture =>
            {
                if (capture)
                {
                    UnmanagedMethods.SetCapture(Handle.Handle);
                }
                else
                {
                    UnmanagedMethods.ReleaseCapture();
                }
            });
#endif
            CreateWindow();
            _framebuffer = new FramebufferManager(_hwnd);
            //if (Win32GlManager.EglFeature != null)
            //    _gl = new EglGlPlatformSurface((EglDisplay)Win32GlManager.EglFeature.Display,
            //        Win32GlManager.EglFeature.DeferredContext, this);

            s_instances.Add(this);
        }
Exemple #23
0
        public async Task SetDataObjectAsync(IDataObject data)
        {
            Dispatcher.UIThread.VerifyAccess();
            var wrapper = new DataObject(data);
            var i       = OleRetryCount;

            while (true)
            {
                var hr = UnmanagedMethods.OleSetClipboard(wrapper);

                if (hr == 0)
                {
                    break;
                }

                if (--i == 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                await Task.Delay(OleRetryDelay);
            }
        }
Exemple #24
0
        protected override IDisposable StartCore(Action <TimeSpan> tick)
        {
            EnsureTimerQueueCreated();
            var msPerFrame = 1000 / FramesPerSecond;

            timerDelegate = (_, __) => tick(TimeSpan.FromMilliseconds(Environment.TickCount));

            UnmanagedMethods.CreateTimerQueueTimer(
                out var timer,
                _timerQueue,
                timerDelegate,
                IntPtr.Zero,
                (uint)msPerFrame,
                (uint)msPerFrame,
                0
                );

            return(Disposable.Create(() =>
            {
                timerDelegate = null;
                UnmanagedMethods.DeleteTimerQueueTimer(_timerQueue, timer, IntPtr.Zero);
            }));
        }
        public async Task SetDataObjectAsync(IDataObject data)
        {
            Dispatcher.UIThread.VerifyAccess();
            using var wrapper = new DataObject(data);
            var i = OleRetryCount;

            while (true)
            {
                var ptr = MicroCom.MicroComRuntime.GetNativeIntPtr <Win32Com.IDataObject>(wrapper);
                var hr  = UnmanagedMethods.OleSetClipboard(ptr);

                if (hr == 0)
                {
                    break;
                }

                if (--i == 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                await Task.Delay(OleRetryDelay);
            }
        }
Exemple #26
0
        public void Resize(Size value)
        {
            int requestedClientWidth  = (int)(value.Width * Scaling);
            int requestedClientHeight = (int)(value.Height * Scaling);

            UnmanagedMethods.RECT clientRect;
            UnmanagedMethods.GetClientRect(_hwnd, out clientRect);

            // do comparison after scaling to avoid rounding issues
            if (requestedClientWidth != clientRect.Width || requestedClientHeight != clientRect.Height)
            {
                UnmanagedMethods.RECT windowRect;
                UnmanagedMethods.GetWindowRect(_hwnd, out windowRect);

                UnmanagedMethods.SetWindowPos(
                    _hwnd,
                    IntPtr.Zero,
                    0,
                    0,
                    requestedClientWidth + (windowRect.Width - clientRect.Width),
                    requestedClientHeight + (windowRect.Height - clientRect.Height),
                    UnmanagedMethods.SetWindowPosFlags.SWP_RESIZE);
            }
        }
Exemple #27
0
        private void ShowWindow(WindowState state)
        {
            UnmanagedMethods.ShowWindowCommand command;

            switch (state)
            {
            case WindowState.Minimized:
                command = UnmanagedMethods.ShowWindowCommand.Minimize;
                break;

            case WindowState.Maximized:
                command = UnmanagedMethods.ShowWindowCommand.Maximize;
                break;

            case WindowState.Normal:
                command = UnmanagedMethods.ShowWindowCommand.Restore;
                break;

            default:
                throw new ArgumentException("Invalid WindowState.");
            }

            UnmanagedMethods.ShowWindow(_hwnd, command);
        }
        public ILockedFramebuffer Lock()
        {
            Monitor.Enter(_lock);

            LockedFramebuffer?fb = null;

            try
            {
                UnmanagedMethods.GetClientRect(_hwnd, out var rc);

                var width  = Math.Max(1, rc.right - rc.left);
                var height = Math.Max(1, rc.bottom - rc.top);

                if (_framebufferData is null || _framebufferData?.Size.Width != width || _framebufferData?.Size.Height != height)
                {
                    _framebufferData?.Dispose();

                    _framebufferData = AllocateFramebufferData(width, height);
                }

                var framebufferData = _framebufferData.Value;

                return(fb = new LockedFramebuffer(
                           framebufferData.Data.Address, framebufferData.Size, framebufferData.RowBytes,
                           GetCurrentDpi(), _format, _onDisposeAction));
            }
            finally
            {
                // We free the lock when for whatever reason framebuffer was not created.
                // This allows for a potential retry later.
                if (fb is null)
                {
                    Monitor.Exit(_lock);
                }
            }
        }
        protected override IntPtr CreateWindowOverride(ushort atom)
        {
            UnmanagedMethods.WindowStyles style =
                UnmanagedMethods.WindowStyles.WS_POPUP |
                UnmanagedMethods.WindowStyles.WS_CLIPSIBLINGS;

            UnmanagedMethods.WindowStyles exStyle =
                UnmanagedMethods.WindowStyles.WS_EX_TOOLWINDOW |
                UnmanagedMethods.WindowStyles.WS_EX_TOPMOST;

            return(UnmanagedMethods.CreateWindowEx(
                       (int)exStyle,
                       atom,
                       null,
                       (uint)style,
                       UnmanagedMethods.CW_USEDEFAULT,
                       UnmanagedMethods.CW_USEDEFAULT,
                       UnmanagedMethods.CW_USEDEFAULT,
                       UnmanagedMethods.CW_USEDEFAULT,
                       IntPtr.Zero,
                       IntPtr.Zero,
                       IntPtr.Zero,
                       IntPtr.Zero));
        }
 internal void UpdateKeyStates()
 {
     UnmanagedMethods.GetKeyboardState(this.keyStates);
 }