Esempio n. 1
0
 public static void DrawThemeTextActive(
     Graphics aGraph,
     string aText,
     Point aLocation,
     SUxTextProperties aProp
     )
 {
     IntPtr lPriHdc = aGraph.GetHdc();
     VisualStyleRenderer lRenderer = new VisualStyleRenderer(VisualStyleElement.Window.Caption.Active);
     DTTOPTS lOpts = new DTTOPTS();
     lOpts.dwSize = Marshal.SizeOf(lOpts);
     lOpts.dwFlags = DTT_COMPOSITED | DTT_GLOWSIZE | DTT_TEXTCOLOR;
     lOpts.crText = ColorTranslator.ToWin32(aProp.color);
     lOpts.iGlowSize = aProp.glowSize;
     RECT ltBounds = new RECT(0, 0, aProp.bounds.Width, aProp.bounds.Height);
     DrawThemeTextEx(
                 lRenderer.Handle,
                 lPriHdc,
                 0, 0,
                 aText,
                 -1,
                 (int)(aProp.flags),
                 ref ltBounds,
                 ref lOpts
             );
 }
Esempio n. 2
0
        public void OnTick_Timer(object sender, EventArgs e)
        {
            ++tick;
            var rem = 5 - (tick / 60);
            if (rem == 0)
            {
                timer.Stop();

                var hWnd = GetForegroundWindow();
                var winRect = new RECT();
                GetWindowRect(hWnd, ref winRect);
                if (X == null && Y == null)
                {
                    X = Screen.PrimaryScreen.Bounds.Width - Screen.PrimaryScreen.WorkingArea.Width + 20;
                    Y = Screen.PrimaryScreen.Bounds.Height - Screen.PrimaryScreen.WorkingArea.Height + 20;
                }
                if (H == null && W == null)
                {
                    W = winRect.right - winRect.left;
                    H = winRect.bottom - winRect.top;
                }
                MoveWindow(hWnd, X.Value, Y.Value, W.Value, H.Value, 0);

                lab_cntdown.Text = "―";
                tick = 0;
                X = Y = H = W = null;
            }
            else if (rem > 0) {
                lab_cntdown.Text = rem.ToString();
            }
        }
		/// <summary>アクティブなウィンドウの画像を取得する</summary>
		/// <returns>アクティブなウィンドウの画像</returns>
		public static Bitmap CaptureActiveWindow()
		{
			//アクティブなウィンドウのデバイスコンテキストを取得
			IntPtr hWnd = GetForegroundWindow();
			IntPtr winDC = GetWindowDC(hWnd);

			//ウィンドウの大きさを取得
			RECT winRect = new RECT();
			GetWindowRect(hWnd, ref winRect);

			Bitmap bmp = new Bitmap(winRect.right - winRect.left, winRect.bottom - winRect.top);

			Graphics g = Graphics.FromImage(bmp);
			IntPtr hDC = g.GetHdc();

			//Bitmapに画像をコピーする
			BitBlt(hDC, 0, 0, bmp.Width, bmp.Height, winDC, 0, 0, SRCCOPY);

			//解放
			g.ReleaseHdc(hDC);
			g.Dispose();
			ReleaseDC(hWnd, winDC);

			return bmp;
		}
        public void Show()
        {
            // When opening a dialog from a console we endup on the primary screen
            // Instead we want the slideshow to be opened on the screen where the console is located.
            IntPtr h2 = GetConsoleWindow();
            RECT rect = new RECT();
            GetWindowRect(h2, ref rect);

            HtmlViewer viewer = new HtmlViewer();

            viewer.ShowInTaskbar = false;
            viewer.Show();

            // The window location can only be changed after the dialog is shown...
            viewer.Location = new System.Drawing.Point(rect.left, rect.top);
            viewer.WindowState = FormWindowState.Maximized;

            Cursor.Hide();

            viewer.Activate();
            SetForegroundWindow(viewer.Handle);

            while (!viewer.IsDisposed)
            {
                Application.DoEvents();
                Thread.Sleep(20);
            }

        }
 public static Size GetWindowSize(IntPtr hWnd)
 {
   IntPtr winDC = GetWindowDC(hWnd);
   RECT rect = new RECT();
   GetWindowRect(hWnd, ref rect);
   return new Size(rect.right - rect.left, rect.bottom - rect.top);
 }
Esempio n. 6
0
        public static Bitmap takeScreenshot()
        {
            try {
                RECT Rect = new RECT();
                if (ReadMemoryManager.FlashClient) {
                    Screen screen = Screen.FromControl(MainForm.mainForm);

                    Rect.left = screen.Bounds.Left;
                    Rect.right = screen.Bounds.Right;
                    Rect.top = screen.Bounds.Top;
                    Rect.bottom = screen.Bounds.Bottom;
                } else {
                    Process tibia_process = ProcessManager.GetTibiaProcess();
                    if (tibia_process == null) return null; //no tibia to take screenshot of

                    if (!GetWindowRect(tibia_process.MainWindowHandle, ref Rect)) return null;
                }

                Bitmap bitmap = new Bitmap(Rect.right - Rect.left, Rect.bottom - Rect.top);
                using (Graphics gr = Graphics.FromImage(bitmap)) {
                    gr.CopyFromScreen(new Point(Rect.left, Rect.top), Point.Empty, bitmap.Size);
                }
                return bitmap;
            } catch(Exception ex) {
                MainForm.mainForm.DisplayWarning("Failed to take screenshot: " + ex.Message);
                return null;
            }
        }
		public void GetBoundsTest()
		{
			RECT rect = new RECT();
			User32.GetWindowRect(_hWnd, ref rect);

			Assert.AreEqual(rect, Window.GetBounds(_hWnd));
		}
Esempio n. 8
0
        private void Form1_Load(object sender, EventArgs e)
        {
            WinApi.SetWindowPos(this.Handle, WinApi.HWND_TOPMOST, 0, 0, 0, 0, WinApi.TOPMOST_FLAGS);
            _refreshThread = new Thread(RefreshThread);

            _sessionMgr = new SessionMgr();

            Layers = new Dictionary<string, ContainerControl>();

            AddHistogram("EXP_HISTOGRAM", "exp", 250, 30, 900, 40, Histogram.HistogramType.Average);
            AddHistogram("EXP_HISTOGRAM2", "exp2", 250, 30, 900, 80, Histogram.HistogramType.Value);
            AddHistogram("JEXP_HISTOGRAM", "jexp", 250, 30, 900, 120, Histogram.HistogramType.Average);

            Layers.Add("CLOCK", new Clock());
            var c = Layers["CLOCK"];
            c.Width = 250;
            c.Height = 250;
            c.Left = 900;
            c.Top = 90;
            this.Controls.Add(Layers["CLOCK"]);

            var rect = new RECT();
            var Ragexes = Process.GetProcessesByName("RagexeRE");
            if (Ragexes.Count() > 0)
            {
                var get = WinApi.GetWindowRect(Ragexes[0].MainWindowHandle, out rect);
                this.Location = new Point(rect.left, rect.top);
                this.Size = new Size(rect.right - rect.left, rect.bottom - rect.top);
            }
            _refreshThread.Start();
        }
Esempio n. 9
0
        public MessageBoxReplacer(IWindowMessageHook hook)
        {
            _hook = hook;

            _hook.WindowMessageReceived += (sender, args) =>
            {
                var senderForm = args.SrcForm;
                if (senderForm == null)
                {
                    return;
                }
                if (args.Message.Msg != WM_APP_CENTERMSG)
                {
                    return;
                }

                var hWnd = GetForegroundWindow();
                if (hWnd == senderForm.Handle)
                {
                    return;
                }

                var r = new RECT();
                GetWindowRect(hWnd, ref r);
                var w = r.right - r.left;
                var h = r.bottom - r.top;
                var x = senderForm.Left + (senderForm.Width - w)/2;
                var y = senderForm.Top + (senderForm.Height - h)/2;
                MoveWindow(hWnd, x, y, w, h, 0);
            };
        }
Esempio n. 10
0
 public static Rectangle GetWindowRect(IntPtr hWnd)
 {
     RECT r = new RECT();
     if (!GetWindowRect(hWnd, out r))
         return new Rectangle();
     else
         return new Rectangle(r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top);
 }
Esempio n. 11
0
        static void Main(string[] args)
        {
            switch (args.Length > 0 ? args[0].Substring(0, 2) : string.Empty)
            {
                case "/c":
                    Application.EnableVisualStyles();

                    var polarisOptions = new OptionsWindow();

                    if (polarisOptions.ShowDialog() == DialogResult.OK)
                    {
                        polarisOptions.SaveSettings();
                    }
                    break;
                case "/p":
                    try
                    {
                        IntPtr previewWindowHandle = new IntPtr(uint.Parse(args[1]));

                        while (!IsWindowVisible(previewWindowHandle))
                        {
                            Application.DoEvents();
                            Thread.Sleep(0);
                        }

                        var previewWindowRect = new RECT();

                        GetClientRect(previewWindowHandle, ref previewWindowRect);

                        int cx = previewWindowRect.right / 2;
                        int cy = previewWindowRect.bottom / 2;
                        int radius = (int)(Math.Min(cx, cy) * 0.8);

                        var previewWindowRectangle = new RectangleF(cx - radius, cy - radius, radius * 2f, radius * 2f);

                        Application.DoEvents();
                        using (var graphics = Graphics.FromHwnd(previewWindowHandle))
                        {
                            graphics.Clear(Properties.Settings.Default.BackColor);

                            Renderer.RenderClock(previewWindowRectangle, graphics, true);

                            graphics.Flush();
                        }
                    }
                    catch
                    {

                    }

                    break;
                default:
                case "/s":
                    ShowScreensaver();
                    break;
            }
        }
		public void Activate(IntPtr hWndParent, RECT[] pRect, int bModal)
		{
            if ((null == pRect) || (0 == pRect.Length))
            {
                throw new ArgumentNullException("pRect");
            }
			Control parentControl = Control.FromHandle(hWndParent);
			RECT pageRectangle = pRect[0];
			MyPageView.Initialize(parentControl, Rectangle.FromLTRB(pageRectangle.left, pageRectangle.top, pageRectangle.right, pageRectangle.bottom));
		}
Esempio n. 13
0
        public static void DrawText(Graphics graphics, string text, Font font, Rectangle bounds, Color color, TextFormatFlags flags, TextStyle textStyle)
        {
            if (!VisualStyleRenderer.IsSupported) {
                TextRenderer.DrawText(graphics, text, font, bounds, color, flags);
                return;
            }

            IntPtr primaryHdc = graphics.GetHdc();

            // Create a memory DC so we can work offscreen
            IntPtr memoryHdc = CreateCompatibleDC(primaryHdc);

            // Create a device-independent bitmap and select it into our DC
            BITMAPINFO info = new BITMAPINFO();
            info.biSize = Marshal.SizeOf(info);
            info.biWidth = bounds.Width;
            info.biHeight = -bounds.Height;
            info.biPlanes = 1;
            info.biBitCount = 32;
            info.biCompression = 0; // BI_RGB
            IntPtr dib = CreateDIBSection(primaryHdc, info, 0, 0, IntPtr.Zero, 0);
            SelectObject(memoryHdc, dib);

            // Create and select font
            IntPtr fontHandle = font.ToHfont();
            SelectObject(memoryHdc, fontHandle);

            // Draw glowing text
            VisualStyleRenderer renderer = new VisualStyleRenderer(System.Windows.Forms.VisualStyles.VisualStyleElement.Window.Caption.Active);
            DTTOPTS dttOpts = new DTTOPTS();
            dttOpts.dwSize = Marshal.SizeOf(typeof(DTTOPTS));

            if (textStyle == TextStyle.Glowing) {
                dttOpts.dwFlags = DTT_COMPOSITED | DTT_GLOWSIZE | DTT_TEXTCOLOR;
            }
            else {
                dttOpts.dwFlags = DTT_COMPOSITED | DTT_TEXTCOLOR;
            }
            dttOpts.crText = ColorTranslator.ToWin32(color);
            dttOpts.iGlowSize = 8; // This is about the size Microsoft Word 2007 uses
            RECT textBounds = new RECT(0, 0, bounds.Right - bounds.Left, bounds.Bottom - bounds.Top);
            DrawThemeTextEx(renderer.Handle, memoryHdc, 0, 0, text, -1, (int)flags, ref textBounds, ref dttOpts);

            // Copy to foreground
            const int SRCCOPY = 0x00CC0020;
            BitBlt(primaryHdc, bounds.Left, bounds.Top, bounds.Width, bounds.Height, memoryHdc, 0, 0, SRCCOPY);

            // Clean up
            DeleteObject(fontHandle);
            DeleteObject(dib);
            DeleteDC(memoryHdc);

            graphics.ReleaseHdc(primaryHdc);
        }
Esempio n. 14
0
        public static Rectangle GetActiveWindowBounds()
        {
            var windowHandle = GetForegroundWindow();

            RECT windowRect = new RECT();
            GetWindowRect(windowHandle, ref windowRect);

            Rectangle bounds = new Rectangle(windowRect.left, windowRect.top, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top);

            return bounds;
        }
    public static void CaptureWindow(IntPtr hWnd, Bitmap bmp, Graphics g)
    {
      IntPtr winDC = GetWindowDC(hWnd);

      RECT winRect = new RECT();
      GetWindowRect(hWnd, ref winRect);

      IntPtr hDC = g.GetHdc();

      BitBlt(hDC, 0, 0, bmp.Width, bmp.Height, winDC, 0, 0, SRCCOPY);
      g.ReleaseHdc(hDC);
    }
        public static bool IsForegroundFullScreen(Screen screen)
        {
            if (screen == null)
            {
                screen = Screen.PrimaryScreen;
            }
            var foregroundWindow = GetForegroundWindow();

            RECT rect = new RECT();
            GetWindowRect(new HandleRef(null, foregroundWindow), ref rect);
            return new System.Drawing.Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top).Contains(screen.Bounds);
        }
Esempio n. 17
0
 public void Activate(IntPtr parent, RECT[] pRect, int bModal)
 {
     if (this.control == null)
     {
         this.control = new CompileOrderViewer(((IProjectManager)item));
         this.control.Size = new Size(pRect[0].right - pRect[0].left, pRect[0].bottom - pRect[0].top);
         this.control.Visible = false;
         this.control.Size = new Size(550, 300);
         this.control.CreateControl();
         NativeMethods.SetParent(this.control.Handle, parent);
         this.control.OnPageUpdated += (sender, args) => IsDirty = true;
     }
 }
		public virtual void Activate(IntPtr parent, RECT[] pRect, int bModal)
		{
			if (this.panel == null)
			{
				this.panel = new Panel();
				this.panel.Size = new Size(pRect[0].right - pRect[0].left, pRect[0].bottom - pRect[0].top);
				this.panel.Text = "Settings";// TODO localization
				this.panel.Visible = false;
				this.panel.Size = new Size(550, 300);
				this.panel.CreateControl();
				//NativeMethods.SetParent(this.panel.Handle, parent);
			}
		}
 public void Activate(IntPtr parentHandle, RECT[] pRect, int modal)
 {
     try
     {
         RECT rect = pRect[0];
         this.ConfigurationView.Initialize(Control.FromHandle(parentHandle),
                                           Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom));
     }
     catch (Exception ex)
     {
         Package.UnexpectedExceptionWarning(ex);
         throw;
     }
 }
Esempio n. 20
0
 public static int DrawShadowText(Graphics g, Rectangle bounds, string text, ThemeTextFormat format, Color textColor, Color shadowColor, int shadowOffsetX, int shadowOffsetY)
 {
     int result = 0;
     IntPtr hdc = g.GetHdc();
     try
     {
         RECT r = new RECT(bounds);
         result = DrawShadowText(hdc, text, (uint)text.Length, ref r, (int)format, new COLORREF(textColor), new COLORREF(shadowColor), shadowOffsetX, shadowOffsetY);
     }
     finally
     {
         g.ReleaseHdc(hdc);
     }
     return result;
 }
 private static bool SetWorkspace(RECT rect)
 {
     try
     {
         bool result = SystemParametersInfo(SPI_SETWORKAREA,
                                        (int)IntPtr.Zero,
                                        ref rect,
                                        SPIF_change);
         return result;
     }
     catch (Exception ex)
     {
         Logger.AddError("Unable to set Working Area",null,ex);
         return false;
     }
 }
Esempio n. 22
0
 /// <summary>
 /// makes a screenshot of your current desktop and returns a bitmap
 /// </summary>
 /// <returns></returns>
 public static Bitmap CreateScreenshot()
 {
     IntPtr hWnd = GetDesktopWindow();
     IntPtr hSorceDC = GetWindowDC(hWnd);
     RECT rect = new RECT();
     GetWindowRect(hWnd, ref rect);
     int width = rect.right - rect.left;
     int height = rect.bottom - rect.top;
     IntPtr hDestDC = CreateCompatibleDC(hSorceDC);
     IntPtr hBitmap = CreateCompatibleBitmap(hSorceDC, width, height);
     IntPtr hObject = SelectObject(hDestDC, hBitmap);
     BitBlt(hDestDC, 0, 0, width, height, hSorceDC, 0, 0, SRCCOPY);
     SelectObject(hDestDC, hObject);
     DeleteDC(hDestDC);
     ReleaseDC(hWnd, hSorceDC);
     Bitmap screenshot = Bitmap.FromHbitmap(hBitmap);
     DeleteObject(hBitmap);
     return screenshot;
 }
Esempio n. 23
0
        // 상위 핸들과 클래스명을 받아서, 그 중에 가로 세로 크기가 같은 텍스트박스를 찾아서 핸들값을 반환하는 함수이다.
        public static IntPtr FindSizeWindow(IntPtr hParent, int index, string ChildClassName, int Width, int Height)
        {
            if (index == 0)
                return hParent;
            else
            {
                int ct = 0;
                IntPtr hChild = IntPtr.Zero;

                do
                {
                    hChild = FindWindowEx(hParent, hChild, ChildClassName, null);
                    //        Console.WriteLine("주어진 핸들의 바로 아래 순환 핸들값:{0:X}", hChild.ToInt32());

                    RECT pRect = new RECT();

                    GetWindowRect(hChild, out pRect);           // TwEdit 을 가진 핸들을 넣어 입력창의 좌표 구조체를 얻고, 입력창의 가로 세로 길이를 구한다.

                    pRect.Width = pRect.Right - pRect.Left;   // 입력창의 가로길이
                    pRect.Height = pRect.Bottom - pRect.Top;   // 입력창의 세로길이

                    //       Console.WriteLine("TwEdit 의 가로 길이:{0}", pRect.Width);
                    //       Console.WriteLine("입력된 Width 의 가로 길이:{0}", Width);
                    //       Console.WriteLine("TwEdit 의 세로 길이:{0}", pRect.Height);
                    //       Console.WriteLine("입력된 Height 의 세로 길이:{0}", Height);

                    if (pRect.Width == Width && pRect.Height == Height)   // 입력창의 가로 세로 길이가 같으면 루프를 탈출한다.
                    {
                        break;
                    }

                    if (hChild != IntPtr.Zero)
                    {
                        ++ct;
                    }
                }
                while (ct < index && hChild != IntPtr.Zero);
                {
                    return hChild;
                }
            }
        }
        /// <summary>
        /// Captures an <see cref="Image"/> of the specified window
        /// </summary>
        /// <param name="handle">The handle of the window to capture</param>
        /// <returns>An <see cref="Image"/> of the specified window</returns>
        public static Image CaptureWindow(IntPtr handle)
        {
            IntPtr hdcSrc = GetWindowDC(handle);

            RECT windowRect = new RECT();
            GetWindowRect(handle, windowRect);

            int width = windowRect.right - windowRect.left;
            int height = windowRect.bottom - windowRect.top;

            IntPtr hdcDest = CreateCompatibleDC(hdcSrc);
            IntPtr hBitmap = CreateCompatibleBitmap(hdcSrc, width, height);

            IntPtr hOld = SelectObject(hdcDest, hBitmap);
            BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, SRCCOPY);
            SelectObject(hdcDest, hOld);
            DeleteDC(hdcDest);
            ReleaseDC(handle, hdcSrc);

            Image image = Image.FromHbitmap(hBitmap);
            DeleteObject(hBitmap);

            return image;
        }
Esempio n. 25
0
        protected override void OnPaintBackground(PaintEventArgs e)
        {
            if (hThemeModule != IntPtr.Zero && !DesignMode)
            {
                if (IsThemeActive())
                {
                    IntPtr hdc = IntPtr.Zero;
                    RECT rect = new RECT(0, 0, Width, Height);

                    try
                    {
                        hdc = e.Graphics.GetHdc();
                        DrawThemeParentBackground(this.Handle, hdc, ref rect);
                    }
                    finally
                    {
                        if (hdc != IntPtr.Zero)
                            e.Graphics.ReleaseHdc(hdc);
                    }
                    return;
                }
            }
            base.OnPaintBackground(e);
        }
Esempio n. 26
0
 public static extern int ScrollWindowEx(IntPtr hWnd, int dx, int dy, RECT prcScroll, RECT prcClip, IntPtr hrgnUpdate, IntPtr prcUpdate, uint flags);
Esempio n. 27
0
 public static extern int ScrollWindowEx(HandleRef hWnd, int dx, int dy, IntPtr prcScroll, ref RECT prcClip, IntPtr hrgnUpdate, ref RECT prcUpdate, uint flags);
Esempio n. 28
0
        /// <summary>
        /// Return the edges of the given column.
        /// </summary>
        /// <param name="lv"></param>
        /// <param name="columnIndex"></param>
        /// <returns>A Point holding the left and right co-ords of the column.
        /// -1 means that the sides could not be retrieved.</returns>
        public static Point GetColumnSides(ListView lv, int columnIndex)
        {
            Point sides = new Point(-1, -1);
            IntPtr hdr = NativeMethods.GetHeaderControl(lv);
            if (hdr == IntPtr.Zero)
                return sides;

            RECT r = new RECT();
            IntPtr result = NativeMethods.SendMessageRECT(hdr, HDM_GETITEMRECT, columnIndex, ref r);
            if (result != IntPtr.Zero) {
                int scrollH = 0;
                //NativeMethods.GetScrollPosition(lv.Handle, true);
                sides.X = r.left - scrollH;
                sides.Y = r.right - scrollH;
            }
            return sides;
        }
Esempio n. 29
0
 public static extern IntPtr SendMessageRECT(IntPtr hWnd, int msg, int wParam, ref RECT r);
Esempio n. 30
0
		public static extern bool GetWindowRect( HandleRef hWnd, out RECT lpRect );
Esempio n. 31
0
 public static extern bool DrawEdge(HandleRef hDC, ref RECT rect, int edge, int flags);
Esempio n. 32
0
 public static extern bool ScrollWindow(HandleRef hWnd, int nXAmount, int nYAmount, ref RECT rectScrollRegion, ref RECT rectClip);
Esempio n. 33
0
            public unsafe DCMapping(IntPtr hDC, Rectangle bounds)
            {
                if (hDC == IntPtr.Zero)
                {
                    throw new ArgumentNullException(nameof(hDC));
                }

                bool   success;
                IntPtr hOriginalClippingRegion = IntPtr.Zero;

                _translatedBounds = bounds;
                _graphics         = null;
                _dc = DeviceContext.FromHdc(hDC);
                _dc.SaveHdc();

                // Retrieve the x-coordinates and y-coordinates of the viewport origin for the specified device context.
                success = Gdi32.GetViewportOrgEx(hDC, out Point viewportOrg).IsTrue();
                Debug.Assert(success, "GetViewportOrgEx() failed.");

                // Create a new rectangular clipping region based off of the bounds specified, shifted over by the x & y specified in the viewport origin.
                IntPtr hClippingRegion = Gdi32.CreateRectRgn(viewportOrg.X + bounds.Left, viewportOrg.Y + bounds.Top, viewportOrg.X + bounds.Right, viewportOrg.Y + bounds.Bottom);

                Debug.Assert(hClippingRegion != IntPtr.Zero, "CreateRectRgn() failed.");

                try
                {
                    // Create an empty region oriented at 0,0 so we can populate it with the original clipping region of the hDC passed in.
                    hOriginalClippingRegion = Gdi32.CreateRectRgn(0, 0, 0, 0);
                    Debug.Assert(hOriginalClippingRegion != IntPtr.Zero, "CreateRectRgn() failed.");

                    // Get the clipping region from the hDC: result = {-1 = error, 0 = no region, 1 = success} per MSDN
                    int result = Gdi32.GetClipRgn(hDC, hOriginalClippingRegion);
                    Debug.Assert(result != -1, "GetClipRgn() failed.");

                    // Shift the viewpoint origint by coordinates specified in "bounds".
                    var lastViewPort = new Point();
                    success = Gdi32.SetViewportOrgEx(hDC, viewportOrg.X + bounds.Left, viewportOrg.Y + bounds.Top, &lastViewPort).IsTrue();
                    Debug.Assert(success, "SetViewportOrgEx() failed.");

                    RegionType originalRegionType;
                    if (result != 0)
                    {
                        // Get the origninal clipping region so we can determine its type (we'll check later if we've restored the region back properly.)
                        RECT originalClipRect = new RECT();
                        originalRegionType = Gdi32.GetRgnBox(hOriginalClippingRegion, ref originalClipRect);
                        Debug.Assert(originalRegionType != RegionType.ERROR, "ERROR returned from SelectClipRgn while selecting the original clipping region..");

                        if (originalRegionType == RegionType.SIMPLEREGION)
                        {
                            // Find the intersection of our clipping region and the current clipping region (our parent's)
                            //      Returns a NULLREGION, the two didn't intersect.
                            //      Returns a SIMPLEREGION, the two intersected
                            //      Resulting region (stuff that was in hOriginalClippingRegion AND hClippingRegion is placed in hClippingRegion
                            RegionType combineResult = Gdi32.CombineRgn(hClippingRegion, hClippingRegion, hOriginalClippingRegion, Gdi32.CombineMode.RGN_AND);
                            Debug.Assert((combineResult == RegionType.SIMPLEREGION) ||
                                         (combineResult == RegionType.NULLREGION),
                                         "SIMPLEREGION or NULLREGION expected.");
                        }
                    }
                    else
                    {
                        // If there was no clipping region, then the result is a simple region.
                        // We don't need to keep track of the original now, since it is empty.
                        Gdi32.DeleteObject(hOriginalClippingRegion);
                        hOriginalClippingRegion = IntPtr.Zero;
                        originalRegionType      = RegionType.SIMPLEREGION;
                    }

                    // Select the new clipping region; make sure it's a SIMPLEREGION or NULLREGION
                    RegionType selectResult = Gdi32.SelectClipRgn(hDC, hClippingRegion);
                    Debug.Assert((selectResult == RegionType.SIMPLEREGION ||
                                  selectResult == RegionType.NULLREGION),
                                 "SIMPLEREGION or NULLLREGION expected.");
                }
                catch (Exception ex) when(!ClientUtils.IsSecurityOrCriticalException(ex))
                {
                    _dc.RestoreHdc();
                    _dc.Dispose();
                }
                finally
                {
                    // Delete the new clipping region, as the clipping region for the HDC is now set
                    // to this rectangle. Hold on to hOriginalClippingRegion, as we'll need to restore
                    // it when this object is disposed.
                    success = Gdi32.DeleteObject(hClippingRegion).IsTrue();
                    Debug.Assert(success, "DeleteObject(hClippingRegion) failed.");

                    if (hOriginalClippingRegion != IntPtr.Zero)
                    {
                        success = Gdi32.DeleteObject(hOriginalClippingRegion).IsTrue();
                        Debug.Assert(success, "DeleteObject(hOriginalClippingRegion) failed.");
                    }
                }
            }
 public extern static int DrawText(IntPtr hdc, string lpString, int nCount, ref RECT lpRect, int uFormat);