public static Padding GetNonClientSize(Control control) { var memory = IntPtr.Zero; try { var rect = new NativeMethods.RECT { left = 0, top = 0, right = control.Width, bottom = control.Height }; memory = Marshal.AllocHGlobal(Marshal.SizeOf(rect)); Marshal.StructureToPtr(rect, memory, false); NativeMethods.SendMessage(control.Handle, NativeMethods.WM_NCCALCSIZE, IntPtr.Zero, memory); rect = (NativeMethods.RECT)Marshal.PtrToStructure(memory, typeof(NativeMethods.RECT)); return new Padding( rect.left, rect.top, control.Width - rect.right, control.Height - rect.bottom ); } finally { if (memory != IntPtr.Zero) Marshal.FreeHGlobal(memory); } }
/// <summary> /// Captures a screenshot of the window associated with the handle argument. /// </summary> /// <param name="handle">Used to determine which window to provide a screenshot for.</param> /// <returns>Screenshot of the window corresponding to the handle argument.</returns> public static Image CaptureWindow(IntPtr handle) { IntPtr sourceContext = NativeMethods.GetWindowDC(handle); IntPtr destinationContext = NativeMethods.CreateCompatibleDC(sourceContext); NativeMethods.RECT windowRect = new NativeMethods.RECT(); NativeMethods.GetWindowRect(handle, ref windowRect); int width = windowRect.right - windowRect.left; int height = windowRect.bottom - windowRect.top; IntPtr bitmap = NativeMethods.CreateCompatibleBitmap(sourceContext, width, height); IntPtr replaceContext = NativeMethods.SelectObject(destinationContext, bitmap); NativeMethods.BitBlt(destinationContext, 0, 0, width, height, sourceContext, 0, 0, NativeMethods.SRCCOPY); NativeMethods.SelectObject(destinationContext, replaceContext); NativeMethods.DeleteDC(destinationContext); NativeMethods.ReleaseDC(handle, sourceContext); Image img = Image.FromHbitmap(bitmap); NativeMethods.DeleteObject(bitmap); return img; }
public void DrawText(string text, Point point, Font font, Color foreColor) { IntPtr fontHandle = font.ToHfont(); IntPtr oldFontHandle = NativeMethods.SelectObject(this.graphicsHandle, fontHandle); int oldBkMode = NativeMethods.SetBkMode(this.graphicsHandle, NativeMethods.TRANSPARENT); int oldTextColor = NativeMethods.SetTextColor(this.graphicsHandle, Color.FromArgb(0, foreColor.R, foreColor.G, foreColor.B).ToArgb()); Size size = this.MeassureTextInternal(text); NativeMethods.RECT clip = new NativeMethods.RECT(); clip.left = point.X; clip.top = point.Y; clip.right = clip.left + size.Width; clip.bottom = clip.top + size.Height; // ExtTextOut does not show Mnemonics highlighting. NativeMethods.DrawText(this.graphicsHandle, text, text.Length, ref clip, NativeMethods.DT_SINGLELINE | NativeMethods.DT_LEFT); NativeMethods.SetTextColor(this.graphicsHandle, oldTextColor); NativeMethods.SetBkMode(this.graphicsHandle, oldBkMode); NativeMethods.SelectObject(this.graphicsHandle, oldFontHandle); NativeMethods.DeleteObject(fontHandle); }
/// <summary> /// Measure a multiline string /// </summary> /// <param name="gr">Graphics</param> /// <param name="text">string to measure</param> /// <param name="rect">Original rect. The width will be taken as fixed.</param> /// <param name="textboxControl">True if you want to measure the string for a textbox control</param> /// <returns>A Size object with the measure of the string according with the params</returns> public static Size GetBestSize(Graphics gr, string text, Rectangle rect, bool textboxControl) { NativeMethods.RECT bounds = new NativeMethods.RECT(rect); IntPtr hdc = gr.GetHdc(); int flags = NativeMethods.DT_CALCRECT | NativeMethods.DT_WORDBREAK; if (textboxControl) flags |= NativeMethods.DT_EDITCONTROL; NativeMethods.DrawText(hdc, text, text.Length, ref bounds, flags); gr.ReleaseHdc(hdc); return new Size(bounds.right - bounds.left, bounds.bottom - bounds.top + (textboxControl ? 6 : 0)); }
public static bool ShouldShowPopup(System.Windows.Forms.Form popupForm, Screen popupScreen) { // Is the current session locked? if (_sessionLocked) return false; // Has the last mouse movement or keyboard action been too long ago? var lii = new NativeMethods.LASTINPUTINFO(); lii.cbSize = (uint)Marshal.SizeOf(lii); bool fResult = NativeMethods.GetLastInputInfo(ref lii); if (!fResult) throw new Exception("GetLastInputInfo failed"); if (NativeMethods.GetTickCount() - lii.dwTime > IdleTime) { return false; } // Only consider the foreground window when it is on the same monitor // as the popup is going to be displayed on. var hForeground = NativeMethods.GetForegroundWindow(); var screen = Screen.FromHandle(hForeground); if (screen.WorkingArea != popupScreen.WorkingArea) { return true; } // Is the foreground application running in full-screen mode? NativeMethods.RECT rcForeground = new NativeMethods.RECT(); NativeMethods.GetClientRect(hForeground, ref rcForeground); var foreground = ClientToScreen(hForeground, rcForeground); // If the client rect is covering the entire screen, the application is a // full-screen application. return !( screen.Bounds.Left >= foreground.Left && screen.Bounds.Top >= foreground.Top && screen.Bounds.Right <= foreground.Right && screen.Bounds.Bottom <= foreground.Bottom ); }
public Padding GetBorderThickness() { var rect = new NativeMethods.RECT(Rectangle.Empty); NativeMethods.AdjustWindowRectEx( ref rect, (uint)NativeMethods.GetWindowLong(Handle, NativeMethods.GWL_STYLE), false, (uint)NativeMethods.GetWindowLong(Handle, NativeMethods.GWL_EXSTYLE) ); return new Padding( rect.right, rect.bottom, rect.right, rect.bottom ); }
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.CenterToParent"]/*' /> /// <devdoc> /// Centers the dialog to its parent. /// </devdoc> /// <internalonly/> protected void CenterToParent() { if (TopLevel) { Point p = new Point(); Size s = Size; IntPtr ownerHandle = IntPtr.Zero; ownerHandle = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT); if (ownerHandle != IntPtr.Zero) { Screen desktop = Screen.FromHandleInternal(ownerHandle); Rectangle screenRect = desktop.WorkingArea; NativeMethods.RECT ownerRect = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(null, ownerHandle), ref ownerRect); p.X = (ownerRect.left + ownerRect.right - s.Width) / 2; if (p.X < screenRect.X) p.X = screenRect.X; else if (p.X + s.Width > screenRect.X + screenRect.Width) p.X = screenRect.X + screenRect.Width - s.Width; p.Y = (ownerRect.top + ownerRect.bottom - s.Height) / 2; if (p.Y < screenRect.Y) p.Y = screenRect.Y; else if (p.Y + s.Height > screenRect.Y + screenRect.Height) p.Y = screenRect.Y + screenRect.Height - s.Height; Location = p; } else { CenterToScreen(); } } }
private void DrawWindow(IntPtr hRgn) { Region clipRegion = null; if (hRgn != (IntPtr)1) { clipRegion = Region.FromHrgn(hRgn); } var borderSize = ParentForm.BorderSize; //borderSize = borderSize == 0 ? 1 : borderSize; NativeMethods.RECT windowRect = new NativeMethods.RECT(); NativeMethods.GetWindowRect(FormHandle, ref windowRect); NativeMethods.OffsetRect(ref windowRect, -windowRect.Left, -windowRect.Top); NativeMethods.RECT clientRect = new NativeMethods.RECT(); NativeMethods.GetWindowRect(FormHandle, ref clientRect); NativeMethods.OffsetRect(ref clientRect, -clientRect.Left, -clientRect.Top); NativeMethods.OffsetRect(ref clientRect, -borderSize, -borderSize); IntPtr hDC = NativeMethods.GetWindowDC(FormHandle); try { using (var g = Graphics.FromHdc(hDC)) { var height = windowRect.Bottom; var width = windowRect.Right; if (borderSize > 0) { using (var pen = new Pen(ParentForm.BorderColor, borderSize)) { g.DrawLine(pen, 0, 0, 0, height); } using (var pen = new Pen(ParentForm.BorderColor, borderSize)) { g.DrawLine(pen, 0, 0, width, 0); } using (var pen = new Pen(ParentForm.BorderColor, borderSize)) { g.DrawLine(pen, width - borderSize, 0, width - borderSize, height); } using (var pen = new Pen(ParentForm.BorderColor, borderSize)) { g.DrawLine(pen, 0, height - borderSize, width, height - borderSize); } } formBorder?.RefreshShadow(width, height); } } finally { NativeMethods.ExcludeClipRect(hDC, -borderSize, -borderSize, clientRect.Right + borderSize, clientRect.Bottom + borderSize); NativeMethods.ReleaseDC(FormHandle, hDC); } }
public static extern bool ValidateRect(HandleRef hWnd, [In][Out] ref NativeMethods.RECT rect);
public static extern bool InvalidateRect(HandleRef hWnd, ref NativeMethods.RECT rect, bool erase);
public static extern int FillRect(HandleRef hdc, [In] ref NativeMethods.RECT rect, HandleRef hbrush);
/// <devdoc> /// Subclassed window procedure for the edit and list child controls of the /// combo box. /// </devdoc> /// <internalonly/> private void ChildWndProc(ref Message m) { switch (m.Msg) { case NativeMethods.WM_CHAR: if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) { DefChildWndProc(ref m); } else { if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) { if (ProcessKeyMessage(ref m)) { return; } DefChildWndProc(ref m); } } break; case NativeMethods.WM_SYSCHAR: if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) { DefChildWndProc(ref m); } else { if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) { if (ProcessKeyEventArgs(ref m)) { return; } DefChildWndProc(ref m); } } break; case NativeMethods.WM_KEYDOWN: case NativeMethods.WM_SYSKEYDOWN: if (SystemAutoCompleteEnabled && !ACNativeWindow.AutoCompleteActive) { finder.FindDropDowns(false); } if (AutoCompleteMode != AutoCompleteMode.None) { char keyChar = unchecked((char)(long)m.WParam); if (keyChar == (char)(int)Keys.Escape) { this.DroppedDown = false; } else if (keyChar == (char)(int)Keys.Return && this.DroppedDown) { UpdateText(); OnSelectionChangeCommittedInternal(EventArgs.Empty); this.DroppedDown = false; } } if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) { DefChildWndProc(ref m); } else { if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) { if (ProcessKeyMessage(ref m)) { return; } DefChildWndProc(ref m); } } break; case NativeMethods.WM_INPUTLANGCHANGE: DefChildWndProc( ref m ); break; case NativeMethods.WM_KEYUP: case NativeMethods.WM_SYSKEYUP: if (DropDownStyle == ComboBoxStyle.Simple && m.HWnd == childListBox.Handle) { DefChildWndProc(ref m); } else { if (PreProcessControlMessage(ref m) != PreProcessControlState.MessageProcessed) { if (ProcessKeyMessage(ref m)) { return; } DefChildWndProc(ref m); } } if (SystemAutoCompleteEnabled && !ACNativeWindow.AutoCompleteActive) { finder.FindDropDowns(); } break; case NativeMethods.WM_KILLFOCUS: // Consider - If we dont' have a childwndproc, then we don't get here, so we don't // update the cache. Do we need to? This happens when we have a DropDownList. if (!DesignMode) { OnImeContextStatusChanged( m.HWnd ); } DefChildWndProc(ref m); // We don't want to fire the focus events twice - // once in the combobox and once here. if (fireLostFocus) { OnLostFocus(EventArgs.Empty); } if (FlatStyle == FlatStyle.Popup) { this.Invalidate(); } break; case NativeMethods.WM_SETFOCUS: // Consider - If we dont' have a childwndproc, then we don't get here, so we don't // set the status. Do we need to? This happens when we have a DropDownList. if (!DesignMode) { ImeContext.SetImeStatus(CachedImeMode, m.HWnd); } if (!HostedInWin32DialogManager) { IContainerControl c = GetContainerControlInternal(); if (c != null) { ContainerControl container = c as ContainerControl; if (container != null) { if (!container.ActivateControlInternal(this, false)) { return; } } } } DefChildWndProc(ref m); // We don't want to fire the focus events twice - // once in the combobox and once here. if (fireSetFocus) { OnGotFocus(EventArgs.Empty); } if (FlatStyle == FlatStyle.Popup) { this.Invalidate(); } break; case NativeMethods.WM_SETFONT: DefChildWndProc(ref m); if (childEdit != null && m.HWnd == childEdit.Handle) { UnsafeNativeMethods.SendMessage(new HandleRef(this, childEdit.Handle), NativeMethods.EM_SETMARGINS, NativeMethods.EC_LEFTMARGIN | NativeMethods.EC_RIGHTMARGIN, 0); } break; case NativeMethods.WM_LBUTTONDBLCLK: //the Listbox gets WM_LBUTTONDOWN - WM_LBUTTONUP -WM_LBUTTONDBLCLK - WM_LBUTTONUP... //sequence for doubleclick... //Set MouseEvents... mousePressed = true; mouseEvents = true; CaptureInternal = true; //Call the DefWndProc() so that mousemove messages get to the windows edit(112079) // DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... // Point Ptlc = EditToComboboxMapping(m); OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, Ptlc.X, Ptlc.Y, 0)); break; case NativeMethods.WM_MBUTTONDBLCLK: //the Listbox gets WM_LBUTTONDOWN - WM_LBUTTONUP -WM_LBUTTONDBLCLK - WM_LBUTTONUP... //sequence for doubleclick... //Set MouseEvents... mousePressed = true; mouseEvents = true; CaptureInternal = true; //Call the DefWndProc() so that mousemove messages get to the windows edit(112079) // DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... // Point Ptmc = EditToComboboxMapping(m); OnMouseDown(new MouseEventArgs(MouseButtons.Middle, 1, Ptmc.X, Ptmc.Y, 0)); break; case NativeMethods.WM_RBUTTONDBLCLK: //the Listbox gets WM_LBUTTONDOWN - WM_LBUTTONUP -WM_LBUTTONDBLCLK - WM_LBUTTONUP... //sequence for doubleclick... //Set MouseEvents... mousePressed = true; mouseEvents = true; CaptureInternal = true; //Call the DefWndProc() so that mousemove messages get to the windows edit(112079) // DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... // Point Ptrc = EditToComboboxMapping(m); OnMouseDown(new MouseEventArgs(MouseButtons.Right, 1, Ptrc.X, Ptrc.Y, 0)); break; case NativeMethods.WM_LBUTTONDOWN: mousePressed = true; mouseEvents = true; //set the mouse capture .. this is the Child Wndproc.. // CaptureInternal = true; DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... // Point Ptl = EditToComboboxMapping(m); OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, Ptl.X, Ptl.Y, 0)); break; case NativeMethods.WM_LBUTTONUP: // Get the mouse location // NativeMethods.RECT r = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref r); Rectangle ClientRect = new Rectangle(r.left, r.top, r.right - r.left, r.bottom - r.top); // Get the mouse location // int x = NativeMethods.Util.SignedLOWORD(m.LParam); int y = NativeMethods.Util.SignedHIWORD(m.LParam); Point pt = new Point(x, y); pt = PointToScreen(pt); // combo box gets a WM_LBUTTONUP for focus change ... // So check MouseEvents.... if (mouseEvents && !ValidationCancelled) { mouseEvents = false; if (mousePressed) { if (ClientRect.Contains(pt)) { mousePressed = false; OnClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); OnMouseClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); } else { mousePressed = false; mouseInEdit = false; OnMouseLeave(EventArgs.Empty); } } } DefChildWndProc(ref m); CaptureInternal = false; //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... // pt = EditToComboboxMapping(m); OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, pt.X, pt.Y, 0)); break; case NativeMethods.WM_MBUTTONDOWN: mousePressed = true; mouseEvents = true; //set the mouse capture .. this is the Child Wndproc.. // CaptureInternal = true; DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... // Point P = EditToComboboxMapping(m); OnMouseDown(new MouseEventArgs(MouseButtons.Middle, 1, P.X, P.Y, 0)); break; case NativeMethods.WM_RBUTTONDOWN: mousePressed = true; mouseEvents = true; //set the mouse capture .. this is the Child Wndproc.. // Bug# 112108: If I set the capture=true here, the // DefWndProc() never fires the WM_CONTEXTMENU that would show // the default context menu. // if (this.ContextMenu != null || this.ContextMenuStrip != null) CaptureInternal = true; DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... // Point Pt = EditToComboboxMapping(m); OnMouseDown(new MouseEventArgs(MouseButtons.Right, 1, Pt.X, Pt.Y, 0)); break; case NativeMethods.WM_MBUTTONUP: mousePressed = false; mouseEvents = false; //set the mouse capture .. this is the Child Wndproc.. // CaptureInternal = false; DefChildWndProc(ref m); OnMouseUp(new MouseEventArgs(MouseButtons.Middle, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); break; case NativeMethods.WM_RBUTTONUP: mousePressed = false; mouseEvents = false; //set the mouse capture .. this is the Child Wndproc.. // if (this.ContextMenu != null) CaptureInternal = false; DefChildWndProc(ref m); //the up gets fired from "Combo-box's WndPrc --- So Convert these Coordinates to Combobox coordianate... // Point ptRBtnUp = EditToComboboxMapping(m); OnMouseUp(new MouseEventArgs(MouseButtons.Right, 1, ptRBtnUp.X, ptRBtnUp.Y, 0)); break; case NativeMethods.WM_CONTEXTMENU: // Forward context menu messages to the parent control if (this.ContextMenu != null || this.ContextMenuStrip != null) { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.WM_CONTEXTMENU, m.WParam, m.LParam); } else { DefChildWndProc(ref m); } break; case NativeMethods.WM_MOUSEMOVE: Point point = EditToComboboxMapping(m); //Call the DefWndProc() so that mousemove messages get to the windows edit(112079) // DefChildWndProc(ref m); OnMouseEnterInternal(EventArgs.Empty); OnMouseMove(new MouseEventArgs(MouseButtons, 0, point.X, point.Y, 0)); break; case NativeMethods.WM_SETCURSOR: if (Cursor != DefaultCursor && childEdit != null && m.HWnd == childEdit.Handle && NativeMethods.Util.LOWORD(m.LParam) == NativeMethods.HTCLIENT) { Cursor.CurrentInternal = Cursor; } else { DefChildWndProc(ref m); } break; case NativeMethods.WM_MOUSELEAVE: DefChildWndProc(ref m); OnMouseLeaveInternal(EventArgs.Empty); break; default: DefChildWndProc(ref m); break; } }
// this eliminates flicker by removing the pieces we're going to paint ourselves from // the update region. Note the UpdateRegionBox is the bounding box of the actual update region. // this is just here so we can quickly eliminate rectangles that arent in the update region. public void ValidateOwnerDrawRegions(ComboBox comboBox, Rectangle updateRegionBox) { NativeMethods.RECT validRect; if (comboBox != null) { return; } Rectangle topOwnerDrawArea = new Rectangle(0,0,comboBox.Width, innerBorder.Top); Rectangle bottomOwnerDrawArea = new Rectangle(0,innerBorder.Bottom,comboBox.Width, comboBox.Height-innerBorder.Bottom); Rectangle leftOwnerDrawArea = new Rectangle(0,0,innerBorder.Left, comboBox.Height); Rectangle rightOwnerDrawArea = new Rectangle(innerBorder.Right,0,comboBox.Width - innerBorder.Right,comboBox.Height); if (topOwnerDrawArea.IntersectsWith(updateRegionBox)) { validRect = new NativeMethods.RECT(topOwnerDrawArea); SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); } if (bottomOwnerDrawArea.IntersectsWith(updateRegionBox)) { validRect = new NativeMethods.RECT(bottomOwnerDrawArea); SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); } if (leftOwnerDrawArea.IntersectsWith(updateRegionBox)) { validRect = new NativeMethods.RECT(leftOwnerDrawArea); SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); } if (rightOwnerDrawArea.IntersectsWith(updateRegionBox)) { validRect = new NativeMethods.RECT(rightOwnerDrawArea); SafeNativeMethods.ValidateRect(new HandleRef(comboBox, comboBox.Handle), ref validRect); } }
/// <summary> /// Returns a rectangle representing the location of the specified NotifyIcon. (Windows Vista and earlier.) /// </summary> /// <param name="notifyicon">The NotifyIcon whose location should be returned.</param> /// <returns>The location of the specified NotifyIcon.</returns> public static Rect?GetNotifyIconRectLegacy(NotifyIcon notifyicon) { Rect?nirect = null; FieldInfo idFieldInfo = notifyicon.GetType().GetField("id", BindingFlags.NonPublic | BindingFlags.Instance); int niid = (int)idFieldInfo.GetValue(notifyicon); FieldInfo windowFieldInfo = notifyicon.GetType().GetField("window", BindingFlags.NonPublic | BindingFlags.Instance); System.Windows.Forms.NativeWindow nativeWindow = (System.Windows.Forms.NativeWindow)windowFieldInfo.GetValue(notifyicon); IntPtr nihandle = nativeWindow.Handle; if (nihandle == null || nihandle == IntPtr.Zero) { return(null); } // find the handle of the task bar IntPtr taskbarparenthandle = NativeMethods.FindWindow("Shell_TrayWnd", null); if (taskbarparenthandle == (IntPtr)null) { return(null); } // find the handle of the notification area IntPtr naparenthandle = NativeMethods.FindWindowEx(taskbarparenthandle, IntPtr.Zero, "TrayNotifyWnd", null); if (naparenthandle == (IntPtr)null) { return(null); } // make a list of toolbars in the notification area (one of them should contain the icon) List <IntPtr> natoolbarwindows = NativeMethods.GetChildToolbarWindows(naparenthandle); bool found = false; for (int i = 0; !found && i < natoolbarwindows.Count; i++) { IntPtr natoolbarhandle = natoolbarwindows[i]; // retrieve the number of toolbar buttons (i.e. notify icons) int buttoncount = NativeMethods.SendMessage(natoolbarhandle, NativeMethods.TB_BUTTONCOUNT, IntPtr.Zero, IntPtr.Zero).ToInt32(); // get notification area's process id uint naprocessid; NativeMethods.GetWindowThreadProcessId(natoolbarhandle, out naprocessid); // get handle to notification area's process IntPtr naprocesshandle = NativeMethods.OpenProcess(NativeMethods.ProcessAccessFlags.All, false, naprocessid); if (naprocesshandle == IntPtr.Zero) { return(null); } // allocate enough memory within the notification area's process to store the button info we want IntPtr toolbarmemoryptr = NativeMethods.VirtualAllocEx(naprocesshandle, (IntPtr)null, (uint)Marshal.SizeOf(typeof(NativeMethods.TBBUTTON)), NativeMethods.AllocationType.Commit, NativeMethods.MemoryProtection.ReadWrite); if (toolbarmemoryptr == IntPtr.Zero) { return(null); } try { // loop through the toolbar's buttons until we find our notify icon for (int j = 0; !found && j < buttoncount; j++) { int bytesread = -1; // ask the notification area to give us information about the current button NativeMethods.SendMessage(natoolbarhandle, NativeMethods.TB_GETBUTTON, new IntPtr(j), toolbarmemoryptr); // retrieve that information from the notification area's process NativeMethods.TBBUTTON buttoninfo = new NativeMethods.TBBUTTON(); NativeMethods.ReadProcessMemory(naprocesshandle, toolbarmemoryptr, out buttoninfo, Marshal.SizeOf(buttoninfo), out bytesread); if (bytesread != Marshal.SizeOf(buttoninfo)) { return(null); } if (buttoninfo.dwData == IntPtr.Zero) { return(null); } // the dwData field contains a pointer to information about the notify icon: // the handle of the notify icon (an 4/8 bytes) and the id of the notify icon (4 bytes) IntPtr niinfopointer = buttoninfo.dwData; // read the notify icon handle IntPtr nihandlenew; NativeMethods.ReadProcessMemory(naprocesshandle, niinfopointer, out nihandlenew, Marshal.SizeOf(typeof(IntPtr)), out bytesread); if (bytesread != Marshal.SizeOf(typeof(IntPtr))) { return(null); } // read the notify icon id uint niidnew; NativeMethods.ReadProcessMemory(naprocesshandle, niinfopointer + Marshal.SizeOf(typeof(IntPtr)), out niidnew, Marshal.SizeOf(typeof(uint)), out bytesread); if (bytesread != Marshal.SizeOf(typeof(uint))) { return(null); } // if we've found a match if (nihandlenew == nihandle && niidnew == niid) { // check if the button is hidden: if it is, return the rectangle of the 'show hidden icons' button if ((byte)(buttoninfo.fsState & NativeMethods.TBSTATE_HIDDEN) != 0) { nirect = GetNotifyAreaButtonRectangle(); } else { NativeMethods.RECT result = new NativeMethods.RECT(); // get the relative rectangle of the toolbar button (notify icon) NativeMethods.SendMessage(natoolbarhandle, NativeMethods.TB_GETITEMRECT, new IntPtr(j), toolbarmemoryptr); NativeMethods.ReadProcessMemory(naprocesshandle, toolbarmemoryptr, out result, Marshal.SizeOf(result), out bytesread); if (bytesread != Marshal.SizeOf(result)) { return(null); } // find where the rectangle lies in relation to the screen NativeMethods.MapWindowPoints(natoolbarhandle, (IntPtr)null, ref result, 2); nirect = result; } found = true; } } } finally { // free memory within process NativeMethods.VirtualFreeEx(naprocesshandle, toolbarmemoryptr, 0, NativeMethods.FreeType.Release); // close handle to process NativeMethods.CloseHandle(naprocesshandle); } } return(nirect); }
int UnsafeNativeMethods.IDocHostUIHandler.ResizeBorder(NativeMethods.RECT rect, UnsafeNativeMethods.IOleInPlaceUIWindow doc, bool fFrameWindow) { return(UnsafeNativeMethods.HRESULT.S_OK); }
public static extern bool DrawFrameControl(HandleRef hDC, ref NativeMethods.RECT rect, int type, int state);
public static extern int GetRgnBox(HandleRef hRegion, ref NativeMethods.RECT clipRect);
public static extern bool DrawEdge(HandleRef hDC, ref NativeMethods.RECT rect, int edge, int flags);
public static extern bool ScrollWindow(HandleRef hWnd, int nXAmount, int nYAmount, ref NativeMethods.RECT rectScrollRegion, ref NativeMethods.RECT rectClip);
public static extern int ScrollWindowEx(HandleRef hWnd, int nXAmount, int nYAmount, NativeMethods.COMRECT rectScrollRegion, ref NativeMethods.RECT rectClip, HandleRef hrgnUpdate, ref NativeMethods.RECT prcUpdate, int flags);
private void DrawUpDownButton() { bool mouseOver = false; bool mousePress = LeftKeyPressed(); bool mouseInUpButton = false; NativeMethods.RECT rect = new NativeMethods.RECT(); NativeMethods.GetClientRect(base.Handle, ref rect); Rectangle clipRect = Rectangle.FromLTRB( rect.Top, rect.Left, rect.Right, rect.Bottom); Point cursorPoint = new Point(); NativeMethods.GetCursorPos(ref cursorPoint); NativeMethods.GetWindowRect(base.Handle, ref rect); mouseOver = NativeMethods.PtInRect(ref rect, cursorPoint); cursorPoint.X -= rect.Left; cursorPoint.Y -= rect.Top; mouseInUpButton = cursorPoint.X < clipRect.Width / 2; using (Graphics g = Graphics.FromHwnd(base.Handle)) { UpDownButtonPaintEventArgs e = new UpDownButtonPaintEventArgs( g, clipRect, mouseOver, mousePress, mouseInUpButton); _owner.OnPaintUpDownButton(e); } }
public static extern int MapWindowPoints(HandleRef hWndFrom, HandleRef hWndTo, [In, Out] ref NativeMethods.RECT rect, int cPoints);
private void DrawBorder(Graphics g) { if (SelectedIndex != -1) { Rectangle tabRect = GetTabRect(SelectedIndex); Rectangle clipRect = ClientRectangle; Point[] points = new Point[6]; IntPtr upDownButtonHandle = UpDownButtonHandle; bool hasUpDown = upDownButtonHandle != IntPtr.Zero; if (hasUpDown) { if (NativeMethods.IsWindowVisible(upDownButtonHandle)) { NativeMethods.RECT upDownButtonRect = new NativeMethods.RECT(); NativeMethods.GetWindowRect( upDownButtonHandle, ref upDownButtonRect); Rectangle upDownRect = Rectangle.FromLTRB( upDownButtonRect.Left, upDownButtonRect.Top, upDownButtonRect.Right, upDownButtonRect.Bottom); upDownRect = RectangleToClient(upDownRect); tabRect.X = tabRect.X > upDownRect.X ? upDownRect.X : tabRect.X; tabRect.Width = tabRect.Right > upDownRect.X ? upDownRect.X - tabRect.X : tabRect.Width; } } switch (Alignment) { case TabAlignment.Top: points[0] = new Point( tabRect.X, tabRect.Bottom); points[1] = new Point( clipRect.X, tabRect.Bottom); points[2] = new Point( clipRect.X, clipRect.Bottom - 1); points[3] = new Point( clipRect.Right - 1, clipRect.Bottom - 1); points[4] = new Point( clipRect.Right - 1, tabRect.Bottom); points[5] = new Point( tabRect.Right, tabRect.Bottom); break; case TabAlignment.Bottom: points[0] = new Point( tabRect.X, tabRect.Y); points[1] = new Point( clipRect.X, tabRect.Y); points[2] = new Point( clipRect.X, clipRect.Y); points[3] = new Point( clipRect.Right - 1, clipRect.Y); points[4] = new Point( clipRect.Right - 1, tabRect.Y); points[5] = new Point( tabRect.Right, tabRect.Y); break; case TabAlignment.Left: points[0] = new Point( tabRect.Right, tabRect.Y); points[1] = new Point( tabRect.Right, clipRect.Y); points[2] = new Point( clipRect.Right - 1, clipRect.Y); points[3] = new Point( clipRect.Right - 1, clipRect.Bottom - 1); points[4] = new Point( tabRect.Right, clipRect.Bottom - 1); points[5] = new Point( tabRect.Right, tabRect.Bottom); break; case TabAlignment.Right: points[0] = new Point( tabRect.X, tabRect.Y); points[1] = new Point( tabRect.X, clipRect.Y); points[2] = new Point( clipRect.X, clipRect.Y); points[3] = new Point( clipRect.X, clipRect.Bottom - 1); points[4] = new Point( tabRect.X, clipRect.Bottom - 1); points[5] = new Point( tabRect.X, tabRect.Bottom); break; } using (Pen pen = new Pen(_borderColor)) { g.DrawLines(pen, points); } } }
public static extern int MapWindowPoints(NativeMethods.HWND hWndFrom, NativeMethods.HWND hWndTo, [In, Out] ref NativeMethods.RECT rect, int cPoints);
/// <devdoc> /// </devdoc> /// <internalonly/> private void WmEraseBkgnd(ref Message m) { if ((DropDownStyle == ComboBoxStyle.Simple) && ParentInternal != null) { NativeMethods.RECT rect = new NativeMethods.RECT(); SafeNativeMethods.GetClientRect(new HandleRef(this, Handle), ref rect); Control p = ParentInternal; Graphics graphics = Graphics.FromHdcInternal(m.WParam); if (p != null) { Brush brush = new SolidBrush(p.BackColor); graphics.FillRectangle(brush, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); brush.Dispose(); } else { graphics.FillRectangle(SystemBrushes.Control, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); } graphics.Dispose(); m.Result = (IntPtr)1; return; } base.WndProc(ref m); }
public virtual int RenderBackground(IntPtr hdc, int partid, int stateid, Rectangle prect, NativeMethods.RECT pcliprect) { return(Unhandled); }
/// <summary> /// Returns a rectangle representing the location of the specified NotifyIcon. (Windows 7+.) /// </summary> /// <param name="notifyicon">The NotifyIcon whose location should be returned.</param> /// <returns>The location of the specified NotifyIcon. Null if the location could not be found.</returns> public static Rect? GetNotifyIconRectWindows7(NotifyIcon notifyicon) { if (Compatibility.CurrentWindowsVersion != Compatibility.WindowsVersion.Windows7Plus) throw new PlatformNotSupportedException("This method can only be used under Windows 7 or later. Please use GetNotifyIconRectangleLegacy() if you use an earlier operating system."); // get notify icon id FieldInfo idFieldInfo = notifyicon.GetType().GetField("id", BindingFlags.NonPublic | BindingFlags.Instance); int iconid = (int)idFieldInfo.GetValue(notifyicon); // get notify icon hwnd IntPtr iconhandle; try { FieldInfo windowFieldInfo = notifyicon.GetType().GetField("window", BindingFlags.NonPublic | BindingFlags.Instance); System.Windows.Forms.NativeWindow nativeWindow = (System.Windows.Forms.NativeWindow)windowFieldInfo.GetValue(notifyicon); iconhandle = nativeWindow.Handle; if (iconhandle == null || iconhandle == IntPtr.Zero) return null; } catch { return null; } NativeMethods.RECT rect = new NativeMethods.RECT(); NativeMethods.NOTIFYICONIDENTIFIER nid = new NativeMethods.NOTIFYICONIDENTIFIER() { hWnd = iconhandle, uID = (uint)iconid }; nid.cbSize = (uint)Marshal.SizeOf(nid); int result = NativeMethods.Shell_NotifyIconGetRect(ref nid, out rect); // 0 means success, 1 means the notify icon is in the fly-out - either is fine if (result != 0 && result != 1) return null; // convert to System.Rect and return return rect; }
protected Context CreateRenderContext(IntPtr hdc, NativeMethods.RECT clip) => new Context(hdc, clip);
/// <summary> /// Return the bounds of the item with the given index /// </summary> /// <param name="itemIndex"></param> /// <returns></returns> public Rectangle GetItemRect(int itemIndex) { const int HDM_FIRST = 0x1200; const int HDM_GETITEMRECT = HDM_FIRST + 7; NativeMethods.RECT r = new NativeMethods.RECT(); NativeMethods.SendMessageRECT(this.Handle, HDM_GETITEMRECT, itemIndex, ref r); return Rectangle.FromLTRB(r.left, r.top, r.right, r.bottom); }
public Context(IntPtr hdc, NativeMethods.RECT clip) { _hdc = hdc; _clip = clip; _graphicsLazy = new Lazy <Graphics>(CreateGraphics); }
private void DrawTreeItem(string itemText, int imageIndex, IntPtr dc, NativeMethods.RECT rcIn, int state, int backColor, int textColor) { IntNativeMethods.SIZE size = new IntNativeMethods.SIZE(); IntNativeMethods.RECT rc2 = new IntNativeMethods.RECT(); IntNativeMethods.RECT rc = new IntNativeMethods.RECT(rcIn.left, rcIn.top, rcIn.right, rcIn.bottom); ImageList imagelist = this.ImageList; IntPtr hfontOld = IntPtr.Zero; // Select the font of the dialog, so we don't get the underlined font // when the item is being tracked if ((state & STATE_HOT) != 0) { hfontOld = SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(Parent, ((Control)Parent).FontHandle)); } // Fill the background if (((state & STATE_SELECTED) != 0) && (hbrushDither != IntPtr.Zero)) { FillRectDither(dc, rcIn); SafeNativeMethods.SetBkMode(new HandleRef(null, dc), NativeMethods.TRANSPARENT); } else { SafeNativeMethods.SetBkColor(new HandleRef(null, dc), backColor); IntUnsafeNativeMethods.ExtTextOut(new HandleRef(null, dc), 0, 0, NativeMethods.ETO_CLIPPED | NativeMethods.ETO_OPAQUE, ref rc, null, 0, null); } // Get the height of the font IntUnsafeNativeMethods.GetTextExtentPoint32(new HandleRef(null, dc), itemText, size); // Draw the caption rc2.left = rc.left + SIZE_ICON_X + 2 * PADDING_HORZ; rc2.top = rc.top + (((rc.bottom - rc.top) - size.cy) >> 1); rc2.bottom = rc2.top + size.cy; rc2.right = rc.right; SafeNativeMethods.SetTextColor(new HandleRef(null, dc), textColor); IntUnsafeNativeMethods.DrawText(new HandleRef(null, dc), itemText, ref rc2, IntNativeMethods.DT_LEFT | IntNativeMethods.DT_VCENTER | IntNativeMethods.DT_END_ELLIPSIS | IntNativeMethods.DT_NOPREFIX); SafeNativeMethods.ImageList_Draw(new HandleRef(imagelist, imagelist.Handle), imageIndex, new HandleRef(null, dc), PADDING_HORZ, rc.top + (((rc.bottom - rc.top) - SIZE_ICON_Y) >> 1), NativeMethods.ILD_TRANSPARENT); // Draw the hot-tracking border if needed if ((state & STATE_HOT) != 0) { int savedColor; // top left savedColor = SafeNativeMethods.SetBkColor(new HandleRef(null, dc), ColorTranslator.ToWin32(SystemColors.ControlLightLight)); rc2.left = rc.left; rc2.top = rc.top; rc2.bottom = rc.top + 1; rc2.right = rc.right; IntUnsafeNativeMethods.ExtTextOut(new HandleRef(null, dc), 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); rc2.bottom = rc.bottom; rc2.right = rc.left + 1; IntUnsafeNativeMethods.ExtTextOut(new HandleRef(null, dc), 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); // bottom right SafeNativeMethods.SetBkColor(new HandleRef(null, dc), ColorTranslator.ToWin32(SystemColors.ControlDark)); rc2.left = rc.left; rc2.right = rc.right; rc2.top = rc.bottom - 1; rc2.bottom = rc.bottom; IntUnsafeNativeMethods.ExtTextOut(new HandleRef(null, dc), 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); rc2.left = rc.right - 1; rc2.top = rc.top; IntUnsafeNativeMethods.ExtTextOut(new HandleRef(null, dc), 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); SafeNativeMethods.SetBkColor(new HandleRef(null, dc), savedColor); } if (hfontOld != IntPtr.Zero) { SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(null, hfontOld)); } }
private static void GetClippedPositionOffsets(TextEditor This, ITextPointer position, LogicalDirection direction, out double horizontalOffset, out double verticalOffset) { // GetCharacterRect will return the position that base on UiScope. Rect positionRect = position.GetCharacterRect(direction); // Get the base offsets for our ContextMenu. horizontalOffset = positionRect.X; verticalOffset = positionRect.Y + positionRect.Height; // Clip to the child render scope. FrameworkElement element = This.TextView.RenderScope as FrameworkElement; if (element != null) { GeneralTransform transform = element.TransformToAncestor(This.UiScope); if (transform != null) { ClipToElement(element, transform, ref horizontalOffset, ref verticalOffset); } } // Clip to parent visuals. // This is unintuitive -- you might expect parents to have increasingly // larger viewports. But any parent that behaves like a ScrollViewer // will have a smaller view port that we need to clip against. for (Visual visual = This.UiScope; visual != null; visual = VisualTreeHelper.GetParent(visual) as Visual) { element = visual as FrameworkElement; if (element != null) { GeneralTransform transform = visual.TransformToDescendant(This.UiScope); if (transform != null) { ClipToElement(element, transform, ref horizontalOffset, ref verticalOffset); } } } // Clip to the window client rect. PresentationSource source = PresentationSource.CriticalFromVisual(This.UiScope); IWin32Window window = source as IWin32Window; if (window != null) { IntPtr hwnd = IntPtr.Zero; new UIPermission(UIPermissionWindow.AllWindows).Assert(); // BlessedAssert try { hwnd = window.Handle; } finally { CodeAccessPermission.RevertAssert(); } NativeMethods.RECT rc = new NativeMethods.RECT(0, 0, 0, 0); SafeNativeMethods.GetClientRect(new HandleRef(null, hwnd), ref rc); // Convert to mil measure units. Point minPoint = new Point(rc.left, rc.top); Point maxPoint = new Point(rc.right, rc.bottom); CompositionTarget compositionTarget = source.CompositionTarget; minPoint = compositionTarget.TransformFromDevice.Transform(minPoint); maxPoint = compositionTarget.TransformFromDevice.Transform(maxPoint); // Convert to local coordinates. GeneralTransform transform = compositionTarget.RootVisual.TransformToDescendant(This.UiScope); if (transform != null) { transform.TryTransform(minPoint, out minPoint); transform.TryTransform(maxPoint, out maxPoint); // Finally, do the clip. horizontalOffset = ClipToBounds(minPoint.X, horizontalOffset, maxPoint.X); verticalOffset = ClipToBounds(minPoint.Y, verticalOffset, maxPoint.Y); } // ContextMenu code takes care of clipping to desktop. } }
protected override void WndProc(ref Message m) { switch (m.Msg) { case NativeMethods.WindowsMessage.WM_NCACTIVATE: if (m.WParam == IntPtr.Zero) { m.Result = NativeMethods.MESSAGE_HANDLED; } InvalidateWindow(); break; case NativeMethods.WindowsMessage.WM_SETCURSOR: case NativeMethods.WindowsMessage.WM_ACTIVATEAPP: { base.WndProc(ref m); InvalidateWindow(); } break; case NativeMethods.WindowsMessage.WM_NCUAHDRAWCAPTION: case NativeMethods.WindowsMessage.WM_NCUAHDRAWFRAME: { InvalidateWindow(); } break; case NativeMethods.WindowsMessage.WM_NCPAINT: if (NativeMethods.IsWindowVisible(FormHandle)) { DrawWindow(m.WParam); m.Result = NativeMethods.MESSAGE_HANDLED; } break; case NativeMethods.WindowsMessage.WM_NCCALCSIZE: if (m.WParam != IntPtr.Zero) { NativeMethods.NCCALCSIZE_PARAMS ncsize = (NativeMethods.NCCALCSIZE_PARAMS)Marshal.PtrToStructure(m.LParam, typeof(NativeMethods.NCCALCSIZE_PARAMS)); NativeMethods.WINDOWPOS wp = (NativeMethods.WINDOWPOS)Marshal.PtrToStructure(ncsize.lppos, typeof(NativeMethods.WINDOWPOS)); // store original frame sizes if (!_bStoreSize) { _bStoreSize = true; _iCaptionHeight = ncsize.rect2.Top - ncsize.rect0.Top; _iFrameHeight = ncsize.rect0.Bottom - ncsize.rect2.Bottom; _iFrameWidth = ncsize.rect2.Left - ncsize.rect0.Left; } if (!_bResetSize) { ncsize.rect0 = CalculateFrameSize(wp.x, wp.y, wp.cx, wp.cy); ncsize.rect1 = ncsize.rect0; } Marshal.StructureToPtr(ncsize, m.LParam, false); m.Result = (IntPtr)0x400; //WVR_VALIDRECTS; } else { NativeMethods.RECT rc = (NativeMethods.RECT)m.GetLParam(typeof(NativeMethods.RECT)); rc = CalculateFrameSize(rc.Left, rc.Top, rc.Right - rc.Left, rc.Bottom - rc.Top);; Marshal.StructureToPtr(rc, m.LParam, true); m.Result = IntPtr.Zero; //MESSAGE_PROCESS; } base.WndProc(ref m); break; default: base.WndProc(ref m); break; } }
public static extern bool LPtoDP(HandleRef hDC, [In][Out] ref NativeMethods.RECT lpRect, int nCount);
public static extern bool AdjustWindowRectExForDpi(ref NativeMethods.RECT lpRect, int dwStyle, bool bMenu, int dwExStyle, uint dpi);
private static NativeMethods.RECT CenterInRect(NativeMethods.RECT parentRect, int childWidth, int childHeight, NativeMethods.RECT monitorClippingRect) { NativeMethods.RECT result = default(NativeMethods.RECT); result.Left = parentRect.Left + (parentRect.Width - childWidth) / 2; result.Top = parentRect.Top + (parentRect.Height - childHeight) / 2; result.Width = childWidth; result.Height = childHeight; result.Left = Math.Min(result.Right, monitorClippingRect.Right) - result.Width; result.Top = Math.Min(result.Bottom, monitorClippingRect.Bottom) - result.Height; result.Left = Math.Max(result.Left, monitorClippingRect.Left); result.Top = Math.Max(result.Top, monitorClippingRect.Top); return(result); }
/// <include file='doc\ToolBar.uex' path='docs/doc[@for="ToolBar.WmNotifyDropDown"]/*' /> /// <devdoc> /// The button clicked was a dropdown button. If it has a menu specified, /// show it now. Otherwise, fire an onButtonDropDown event. /// </devdoc> /// <internalonly/> private void WmNotifyDropDown(ref Message m) { NativeMethods.NMTOOLBAR nmTB = (NativeMethods.NMTOOLBAR)m.GetLParam(typeof(NativeMethods.NMTOOLBAR)); ToolBarButton tbb = (ToolBarButton)buttons[nmTB.iItem]; if (tbb == null) throw new InvalidOperationException(SR.GetString(SR.ToolBarButtonNotFound)); OnButtonDropDown(new ToolBarButtonClickEventArgs(tbb)); Menu menu = tbb.DropDownMenu; if (menu != null) { NativeMethods.RECT rc = new NativeMethods.RECT(); NativeMethods.TPMPARAMS tpm = new NativeMethods.TPMPARAMS(); SendMessage(NativeMethods.TB_GETRECT, nmTB.iItem, ref rc); if ((menu.GetType()).IsAssignableFrom(typeof(ContextMenu))) { ((ContextMenu)menu).Show(this, new Point(rc.left, rc.bottom)); } else { Menu main = menu.GetMainMenu(); if (main != null) { main.ProcessInitMenuPopup(menu.Handle); } UnsafeNativeMethods.MapWindowPoints(new HandleRef(nmTB.hdr, nmTB.hdr.hwndFrom), NativeMethods.NullHandleRef, ref rc, 2); tpm.rcExclude_left = rc.left; tpm.rcExclude_top = rc.top; tpm.rcExclude_right = rc.right; tpm.rcExclude_bottom = rc.bottom; SafeNativeMethods.TrackPopupMenuEx( new HandleRef(menu, menu.Handle), NativeMethods.TPM_LEFTALIGN | NativeMethods.TPM_LEFTBUTTON | NativeMethods.TPM_VERTICAL, rc.left, rc.bottom, new HandleRef(this, Handle), tpm); } } }
// Microsoft.Internal.VisualStudio.PlatformUI.WindowHelper public static int ShowModal(IAnkhServiceProvider context, Window window, IntPtr parent) { if (window == null) { throw new ArgumentNullException("window"); } IVsUIShell vsUIShell = context.GetService <IVsUIShell>(typeof(SVsUIShell)); if (vsUIShell == null) { throw new COMException("Can't get UI shell", -2147467259); } int hr = vsUIShell.GetDialogOwnerHwnd(out parent); if (hr != 0) { throw new COMException("Can't fetch dialog owner", hr); } hr = vsUIShell.EnableModeless(0); if (hr != 0) { throw new COMException("Can't enter modal mode", hr); } int result; try { WindowInteropHelper helper = new WindowInteropHelper(window); helper.Owner = parent; if (window.WindowStartupLocation == WindowStartupLocation.CenterOwner) { window.SourceInitialized += delegate(object param0, EventArgs param1) { NativeMethods.RECT parentRect = default(NativeMethods.RECT); if (NativeMethods.GetWindowRect(parent, out parentRect)) { HwndSource hwndSource = HwndSource.FromHwnd(helper.Handle); if (hwndSource != null) { Point point = hwndSource.CompositionTarget.TransformToDevice.Transform(new Point(window.ActualWidth, window.ActualHeight)); NativeMethods.RECT rECT = WindowHelper.CenterRectOnSingleMonitor(parentRect, (int)point.X, (int)point.Y); Point point2 = hwndSource.CompositionTarget.TransformFromDevice.Transform(new Point((double)rECT.Left, (double)rECT.Top)); window.WindowStartupLocation = WindowStartupLocation.Manual; window.Left = point2.X; window.Top = point2.Y; } } }; } bool?flag = window.ShowDialog(); result = (flag.HasValue ? (flag.Value ? 1 : 2) : 0); } finally { vsUIShell.EnableModeless(1); } return(result); }
private void DrawTabPages(Graphics g) { Rectangle tabRect; Point cusorPoint = PointToClient(MousePosition); bool hover; bool selected; bool hasSetClip = false; bool alignHorizontal = (Alignment == TabAlignment.Top || Alignment == TabAlignment.Bottom); System.Drawing.Drawing2D.LinearGradientMode mode = alignHorizontal ? System.Drawing.Drawing2D.LinearGradientMode.Vertical : System.Drawing.Drawing2D.LinearGradientMode.Horizontal; if (alignHorizontal) { IntPtr upDownButtonHandle = UpDownButtonHandle; bool hasUpDown = upDownButtonHandle != IntPtr.Zero; if (hasUpDown) { if (NativeMethods.IsWindowVisible(upDownButtonHandle)) { NativeMethods.RECT upDownButtonRect = new NativeMethods.RECT(); NativeMethods.GetWindowRect( upDownButtonHandle, ref upDownButtonRect); Rectangle upDownRect = Rectangle.FromLTRB( upDownButtonRect.Left, upDownButtonRect.Top, upDownButtonRect.Right, upDownButtonRect.Bottom); upDownRect = RectangleToClient(upDownRect); switch (Alignment) { case TabAlignment.Top: upDownRect.Y = 0; break; case TabAlignment.Bottom: upDownRect.Y = ClientRectangle.Height - DisplayRectangle.Height; break; } upDownRect.Height = ClientRectangle.Height; g.SetClip(upDownRect, CombineMode.Exclude); hasSetClip = true; } } } for(int index = 0; index <base.TabCount; index ++) { TabPage page = TabPages[index]; tabRect = GetTabRect(index); hover = tabRect.Contains(cusorPoint); selected = SelectedIndex == index; Color baseColor = _baseColor; Color borderColor = _borderColor; if (selected) { baseColor = GetColor(_baseColor, 0, -45, -30, -14); } else if (hover) { baseColor = GetColor(_baseColor, 0, 35, 24, 9); } RenderTabBackgroundInternal( g, tabRect, baseColor, borderColor, .45F, mode); bool hasImage = DrawTabImage(g, page, tabRect); DrawtabText(g, page, tabRect, hasImage); } if (hasSetClip) { g.ResetClip(); } }
internal NativeMethods.RECT GetSelectedArea() { if (EmptyRect(_selectedArea)) { if (_detectedElementHnd != IntPtr.Zero) { // Bounding rectangle defines the outer limits of the window area var rect = _boundaryDetection.GetBoundaryRect(_detectedElementHnd); System.Windows.Thickness borderThickness; double monitorScaling = 1.0d; NativeMethods.WINDOWPLACEMENT wndPlacement; NativeMethods.GetWindowPlacement(_detectedElementHnd, out wndPlacement); bool fullScreen = wndPlacement.showCmd == NativeMethods.ShowWindowCommands.SW_SHOWMAXIMIZED; var monitor = _boundaryDetection.GetMonitor(_detectedElementHnd); if (monitor != IntPtr.Zero) { var monitorInfo = _screenProps.GetMonitorInformation(monitor); NativeMethods.RECT rcWorkArea = monitorInfo.rcWork; // Calculate monitor scaling relative to primary monitor var monitorScalingFactor = monitorInfo.scalingFactor; var defaultScalingFactor = _screenProps.GetMonitorInformation(IntPtr.Zero).scalingFactor; monitorScaling = monitorScalingFactor / defaultScalingFactor; // Window may be maximized even if SW_SHOWMAXIMIZED is not set - check the monitor work area if (fullScreen || rect.left == rcWorkArea.left && rect.top == rcWorkArea.top && rect.width == (rcWorkArea.right - rcWorkArea.left) && rect.height == (rcWorkArea.bottom - rcWorkArea.top)) { return(new NativeMethods.RECT { left = (int)(rcWorkArea.left * monitorScaling), right = (int)(rcWorkArea.right * monitorScaling), top = (int)(rcWorkArea.top * monitorScaling), bottom = (int)(rcWorkArea.bottom * monitorScaling), }); } // fall through } // Get client rectangle to check if it uses custom or default frame NativeMethods.RECT clientRect; NativeMethods.GetClientRect(_detectedElementHnd, out clientRect); // For normal frames retain 1px border around sides and bottom and leave the window title bar on the top // Owner drawn frames may not have the border - make sure clientRect is left intact borderThickness = new System.Windows.Thickness( Math.Min(Math.Max(_borderWidth - 1, 0), (rect.width - (clientRect.right - clientRect.left)) / 2), 0, Math.Min(Math.Max(_borderWidth - 1, 0), (rect.width - (clientRect.right - clientRect.left)) / 2), Math.Min(Math.Max(_borderHeight - 1, 0), rect.height - (clientRect.bottom - clientRect.top))); return(new NativeMethods.RECT { left = (int)((rect.left + borderThickness.Left) * monitorScaling), right = (int)((rect.right - borderThickness.Right) * monitorScaling), top = (int)((rect.top + borderThickness.Top) * monitorScaling), bottom = (int)((rect.bottom - borderThickness.Bottom) * monitorScaling), }); } } return(_selectedArea); }
/// <devdoc> /// This procedure takes in the message, converts the Edit handle coordinates into Combo Box Coordinates /// </devdoc> /// <internalonly/> internal Point EditToComboboxMapping(Message m) { if (childEdit == null) { return new Point(0, 0); } // Get the Combox Rect ... // NativeMethods.RECT comboRectMid = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref comboRectMid); // //Get the Edit Rectangle... // NativeMethods.RECT editRectMid = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(this, childEdit.Handle), ref editRectMid); //get the delta int comboXMid = NativeMethods.Util.SignedLOWORD(m.LParam) + (editRectMid.left - comboRectMid.left); int comboYMid = NativeMethods.Util.SignedHIWORD(m.LParam) + (editRectMid.top - comboRectMid.top); return (new Point(comboXMid, comboYMid)); }
private void logWindowLocationsToolStripMenuItem_Click(object sender, EventArgs e) { foreach (IDockContent c in this.DockPanel.Documents) { ctlPuttyPanel panel = c as ctlPuttyPanel; if (c != null) { NativeMethods.RECT rect = new NativeMethods.RECT(); NativeMethods.GetWindowRect(panel.AppPanel.AppWindowHandle, ref rect); Point p = panel.PointToScreen(new Point()); Log.InfoFormat( "[{0,-20} {1,8}] WindowLocations: panel={2}, putty={3}, x={4}, y={5}", panel.Text + (panel == panel.DockPanel.ActiveDocument ? "*" : ""), panel.AppPanel.AppWindowHandle, panel.DisplayRectangle, rect, p.X, p.Y); } } }
/// <summary> /// Helper to handle mouseleave /// </summary> /// <param name="args"></param> private void OnMouseLeaveInternal(EventArgs args) { NativeMethods.RECT rect = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref rect); Rectangle Rect = new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); Point p = MousePosition; if (!Rect.Contains(p)) { OnMouseLeave(args); mouseInEdit = false; } }
private void SetDisplayRectLocation(int x, int y, bool preserveContents) { int xDelta = 0; int yDelta = 0; var client = ClientRectangle; var displayRectangle = _displayRect; int minX = Math.Min(client.Width - displayRectangle.Width, 0); int minY = Math.Min(client.Height - displayRectangle.Height, 0); if (x > 0) x = 0; if (x < minX) x = minX; if (y > 0) y = 0; if (y < minY) y = minY; if (displayRectangle.X != x) xDelta = x - displayRectangle.X; if (displayRectangle.Y != y) yDelta = y - displayRectangle.Y; _displayRect.X = x; _displayRect.Y = y; if ((xDelta != 0 || yDelta != 0) && IsHandleCreated && preserveContents) { var cr = ClientRectangle; var rcClip = new NativeMethods.RECT(cr); var rcUpdate = new NativeMethods.RECT(cr); NativeMethods.ScrollWindowEx( new HandleRef(this, Handle), xDelta, yDelta, IntPtr.Zero, ref rcClip, IntPtr.Zero, ref rcUpdate, NativeMethods.SW_INVALIDATE | NativeMethods.SW_SCROLLCHILDREN ); } OnDisplayRectangleChanged(EventArgs.Empty); }
protected override void WndProc(ref Message m) { switch (m.Msg) { // We don't want to fire the focus events twice - // once in the combobox and once in the ChildWndProc. case NativeMethods.WM_SETFOCUS: try { fireSetFocus = false; base.WndProc(ref m); } finally { fireSetFocus = true; } break; case NativeMethods.WM_KILLFOCUS: try { fireLostFocus = false; base.WndProc(ref m); // Nothing to see here... Just keep on walking... VSWhidbey 504477. // Turns out that with Theming off, we don't get quite the same messages as with theming on. // With theming on we get a WM_MOUSELEAVE after a WM_KILLFOCUS even if you use the Tab key // to move focus. Our response to WM_MOUSELEAVE causes us to repaint everything correctly. // With theming off, we do not get a WM_MOUSELEAVE after a WM_KILLFOCUS, and since we don't have a childwndproc // when we are a Flat DropDownList, we need to force a repaint. The easiest way to do this is to send a // WM_MOUSELEAVE to ourselves, since that also sets up the right state. Or... at least the state is the same // as with Theming on. // This is such a @#$(*&#@$ hack. if (!Application.RenderWithVisualStyles && GetStyle(ControlStyles.UserPaint) == false && this.DropDownStyle == ComboBoxStyle.DropDownList && (FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup)) { UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), NativeMethods.WM_MOUSELEAVE, 0, 0); } } finally { fireLostFocus = true; } break; case NativeMethods.WM_CTLCOLOREDIT: case NativeMethods.WM_CTLCOLORLISTBOX: m.Result = InitializeDCForWmCtlColor(m.WParam, m.Msg); break; case NativeMethods.WM_ERASEBKGND: WmEraseBkgnd(ref m); break; case NativeMethods.WM_PARENTNOTIFY: WmParentNotify(ref m); break; case NativeMethods.WM_REFLECT + NativeMethods.WM_COMMAND: WmReflectCommand(ref m); break; case NativeMethods.WM_REFLECT + NativeMethods.WM_DRAWITEM: WmReflectDrawItem(ref m); break; case NativeMethods.WM_REFLECT + NativeMethods.WM_MEASUREITEM: WmReflectMeasureItem(ref m); break; case NativeMethods.WM_LBUTTONDOWN: mouseEvents = true; base.WndProc(ref m); break; case NativeMethods.WM_LBUTTONUP: // Get the mouse location // NativeMethods.RECT r = new NativeMethods.RECT(); UnsafeNativeMethods.GetWindowRect(new HandleRef(this, Handle), ref r); Rectangle ClientRect = new Rectangle(r.left, r.top, r.right - r.left, r.bottom - r.top); int x = NativeMethods.Util.SignedLOWORD(m.LParam); int y = NativeMethods.Util.SignedHIWORD(m.LParam); Point pt = new Point(x, y); pt = PointToScreen(pt); //mouseEvents is used to keep the check that we get the WM_LBUTTONUP after //WM_LBUTTONDOWN or WM_LBUTTONDBLBCLK // combo box gets a WM_LBUTTONUP for focus change ... // if (mouseEvents && !ValidationCancelled) { mouseEvents = false; bool captured = Capture; if (captured && ClientRect.Contains(pt)) { OnClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); OnMouseClick(new MouseEventArgs(MouseButtons.Left, 1, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0)); } base.WndProc(ref m); } else { CaptureInternal = false; DefWndProc(ref m); } break; case NativeMethods.WM_MOUSELEAVE: DefWndProc(ref m); OnMouseLeaveInternal(EventArgs.Empty); break; case NativeMethods.WM_PAINT: if (GetStyle(ControlStyles.UserPaint) == false && (FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup)) { using (WindowsRegion dr = new WindowsRegion(FlatComboBoxAdapter.dropDownRect)) { using (WindowsRegion wr = new WindowsRegion(this.Bounds)) { // Stash off the region we have to update (the base is going to clear this off in BeginPaint) NativeMethods.RegionFlags updateRegionFlags = (NativeMethods.RegionFlags)SafeNativeMethods.GetUpdateRgn(new HandleRef(this, this.Handle), new HandleRef(this, wr.HRegion), true); dr.CombineRegion(wr, dr, RegionCombineMode.DIFF); Rectangle updateRegionBoundingRect = wr.ToRectangle(); FlatComboBoxAdapter.ValidateOwnerDrawRegions(this, updateRegionBoundingRect); // Call the base class to do its painting (with a clipped DC). NativeMethods.PAINTSTRUCT ps = new NativeMethods.PAINTSTRUCT(); IntPtr dc; bool disposeDc = false; if (m.WParam == IntPtr.Zero) { dc = UnsafeNativeMethods.BeginPaint(new HandleRef(this, Handle), ref ps); disposeDc = true; } else { dc = m.WParam; } using (DeviceContext mDC = DeviceContext.FromHdc(dc)) { using (WindowsGraphics wg = new WindowsGraphics(mDC)) { if (updateRegionFlags != NativeMethods.RegionFlags.ERROR) { wg.DeviceContext.SetClip(dr); } m.WParam = dc; DefWndProc(ref m); if (updateRegionFlags != NativeMethods.RegionFlags.ERROR) { wg.DeviceContext.SetClip(wr); } using (Graphics g = Graphics.FromHdcInternal(dc)) { FlatComboBoxAdapter.DrawFlatCombo(this, g); } } } if (disposeDc) { UnsafeNativeMethods.EndPaint(new HandleRef(this, Handle), ref ps); } } return; } } base.WndProc(ref m); break; case NativeMethods.WM_PRINTCLIENT: // all the fancy stuff we do in OnPaint has to happen again in OnPrint. if (GetStyle(ControlStyles.UserPaint) == false && FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup) { DefWndProc(ref m); if ((unchecked( (int) (long)m.LParam) & NativeMethods.PRF_CLIENT) == NativeMethods.PRF_CLIENT) { if (GetStyle(ControlStyles.UserPaint) == false && FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup) { using (Graphics g = Graphics.FromHdcInternal(m.WParam)) { FlatComboBoxAdapter.DrawFlatCombo(this,g); } } return; } } base.WndProc(ref m); return; case NativeMethods.WM_SETCURSOR: base.WndProc(ref m); break; case NativeMethods.WM_SETFONT: //(bug 119265) if (Width == 0) { suppressNextWindosPos = true; } base.WndProc(ref m); break; case NativeMethods.WM_WINDOWPOSCHANGED: if (!suppressNextWindosPos) { base.WndProc(ref m); } suppressNextWindosPos = false; break; case NativeMethods.WM_NCDESTROY: base.WndProc(ref m); ReleaseChildWindow(); break; default: if (m.Msg == NativeMethods.WM_MOUSEENTER) { DefWndProc(ref m); OnMouseEnterInternal(EventArgs.Empty); break; } base.WndProc(ref m); break; } }
private void UpdateSize() { if (this.style == CommandBarStyle.Menu) { int fontHeight = Font.Height; using (Graphics graphics = this.CreateGraphics()) { using (TextGraphics textGraphics = new TextGraphics(graphics)) { foreach (CommandBarItem item in items) { Size textSize = textGraphics.MeasureText(item.Text, this.Font); if (fontHeight < textSize.Height) { fontHeight = textSize.Height; } } } } NativeMethods.SendMessage(this.Handle, NativeMethods.TB_SETBUTTONSIZE, 0, (fontHeight << 16) | 0xffff); } Size size = new Size(0, 0); for (int i = 0; i < items.Count; i++) { NativeMethods.RECT rect = new NativeMethods.RECT(); NativeMethods.SendMessage(Handle, NativeMethods.TB_GETRECT, i, ref rect); int height = rect.bottom - rect.top; if (height > size.Height) { size.Height = height; } size.Width += rect.right - rect.left; CommandBarComboBox comboBox = items[i] as CommandBarComboBox; if ((comboBox != null) && (comboBox.ComboBox != null)) { if (comboBox.ComboBox.Height > size.Height) { size.Height = comboBox.ComboBox.Height; } this.UpdateComboBoxLocation(comboBox, i); } } this.Size = size; }
/// <summary> /// Returns a rectangle representing the location of the specified NotifyIcon. (Windows Vista and earlier.) /// </summary> /// <param name="notifyicon">The NotifyIcon whose location should be returned.</param> /// <returns>The location of the specified NotifyIcon.</returns> public static Rect? GetNotifyIconRectLegacy(NotifyIcon notifyicon) { Rect? nirect = null; FieldInfo idFieldInfo = notifyicon.GetType().GetField("id", BindingFlags.NonPublic | BindingFlags.Instance); int niid = (int)idFieldInfo.GetValue(notifyicon); FieldInfo windowFieldInfo = notifyicon.GetType().GetField("window", BindingFlags.NonPublic | BindingFlags.Instance); System.Windows.Forms.NativeWindow nativeWindow = (System.Windows.Forms.NativeWindow)windowFieldInfo.GetValue(notifyicon); IntPtr nihandle = nativeWindow.Handle; if (nihandle == null || nihandle == IntPtr.Zero) return null; // find the handle of the task bar IntPtr taskbarparenthandle = NativeMethods.FindWindow("Shell_TrayWnd", null); if (taskbarparenthandle == (IntPtr)null) return null; // find the handle of the notification area IntPtr naparenthandle = NativeMethods.FindWindowEx(taskbarparenthandle, IntPtr.Zero, "TrayNotifyWnd", null); if (naparenthandle == (IntPtr)null) return null; // make a list of toolbars in the notification area (one of them should contain the icon) List<IntPtr> natoolbarwindows = NativeMethods.GetChildToolbarWindows(naparenthandle); bool found = false; for (int i = 0; !found && i < natoolbarwindows.Count; i++) { IntPtr natoolbarhandle = natoolbarwindows[i]; // retrieve the number of toolbar buttons (i.e. notify icons) int buttoncount = NativeMethods.SendMessage(natoolbarhandle, NativeMethods.TB_BUTTONCOUNT, IntPtr.Zero, IntPtr.Zero).ToInt32(); // get notification area's process id uint naprocessid; NativeMethods.GetWindowThreadProcessId(natoolbarhandle, out naprocessid); // get handle to notification area's process IntPtr naprocesshandle = NativeMethods.OpenProcess(NativeMethods.ProcessAccessFlags.All, false, naprocessid); if (naprocesshandle == IntPtr.Zero) return null; // allocate enough memory within the notification area's process to store the button info we want IntPtr toolbarmemoryptr = NativeMethods.VirtualAllocEx(naprocesshandle, (IntPtr)null, (uint)Marshal.SizeOf(typeof(NativeMethods.TBBUTTON)), NativeMethods.AllocationType.Commit, NativeMethods.MemoryProtection.ReadWrite); if (toolbarmemoryptr == IntPtr.Zero) return null; try { // loop through the toolbar's buttons until we find our notify icon for (int j = 0; !found && j < buttoncount; j++) { int bytesread = -1; // ask the notification area to give us information about the current button NativeMethods.SendMessage(natoolbarhandle, NativeMethods.TB_GETBUTTON, new IntPtr(j), toolbarmemoryptr); // retrieve that information from the notification area's process NativeMethods.TBBUTTON buttoninfo = new NativeMethods.TBBUTTON(); NativeMethods.ReadProcessMemory(naprocesshandle, toolbarmemoryptr, out buttoninfo, Marshal.SizeOf(buttoninfo), out bytesread); if (bytesread != Marshal.SizeOf(buttoninfo)) return null; if (buttoninfo.dwData == IntPtr.Zero) return null; // the dwData field contains a pointer to information about the notify icon: // the handle of the notify icon (an 4/8 bytes) and the id of the notify icon (4 bytes) IntPtr niinfopointer = buttoninfo.dwData; // read the notify icon handle IntPtr nihandlenew; NativeMethods.ReadProcessMemory(naprocesshandle, niinfopointer, out nihandlenew, Marshal.SizeOf(typeof(IntPtr)), out bytesread); if (bytesread != Marshal.SizeOf(typeof(IntPtr))) return null; // read the notify icon id uint niidnew; NativeMethods.ReadProcessMemory(naprocesshandle, niinfopointer + Marshal.SizeOf(typeof(IntPtr)), out niidnew, Marshal.SizeOf(typeof(uint)), out bytesread); if (bytesread != Marshal.SizeOf(typeof(uint))) return null; // if we've found a match if (nihandlenew == nihandle && niidnew == niid) { // check if the button is hidden: if it is, return the rectangle of the 'show hidden icons' button if ((byte)(buttoninfo.fsState & NativeMethods.TBSTATE_HIDDEN) != 0) { nirect = GetNotifyAreaButtonRectangle(); } else { NativeMethods.RECT result = new NativeMethods.RECT(); // get the relative rectangle of the toolbar button (notify icon) NativeMethods.SendMessage(natoolbarhandle, NativeMethods.TB_GETITEMRECT, new IntPtr(j), toolbarmemoryptr); NativeMethods.ReadProcessMemory(naprocesshandle, toolbarmemoryptr, out result, Marshal.SizeOf(result), out bytesread); if (bytesread != Marshal.SizeOf(result)) return null; // find where the rectangle lies in relation to the screen NativeMethods.MapWindowPoints(natoolbarhandle, (IntPtr)null, ref result, 2); nirect = result; } found = true; } } } finally { // free memory within process NativeMethods.VirtualFreeEx(naprocesshandle, toolbarmemoryptr, 0, NativeMethods.FreeType.Release); // close handle to process NativeMethods.CloseHandle(naprocesshandle); } } return nirect; }
private void AddItems() { NativeMethods.SendMessage(Handle, NativeMethods.TB_BUTTONSTRUCTSIZE, Marshal.SizeOf(typeof(NativeMethods.TBBUTTON)), 0); int extendedStyle = NativeMethods.TBSTYLE_EX_HIDECLIPPEDBUTTONS | NativeMethods.TBSTYLE_EX_DOUBLEBUFFER; if (style == CommandBarStyle.ToolBar) { extendedStyle |= NativeMethods.TBSTYLE_EX_DRAWDDARROWS; } NativeMethods.SendMessage(Handle, NativeMethods.TB_SETEXTENDEDSTYLE, 0, extendedStyle); this.UpdateImageList(); for (int i = 0; i < items.Count; i++) { NativeMethods.TBBUTTON button = new NativeMethods.TBBUTTON(); button.idCommand = i; NativeMethods.SendMessage(this.Handle, NativeMethods.TB_INSERTBUTTON, i, ref button); NativeMethods.TBBUTTONINFO buttonInfo = this.GetButtonInfo(i); NativeMethods.SendMessage(this.Handle, NativeMethods.TB_SETBUTTONINFO, i, ref buttonInfo); } // Add ComboBox controls. this.Controls.Clear(); for (int i = 0; i < items.Count; i++) { CommandBarComboBox comboBox = this.items[i] as CommandBarComboBox; if (comboBox != null) { NativeMethods.RECT rect = new NativeMethods.RECT(); NativeMethods.SendMessage(this.Handle, NativeMethods.TB_GETITEMRECT, i, ref rect); rect.top = rect.top + (((rect.bottom - rect.top) - comboBox.Height) / 2); comboBox.ComboBox.Location = new Point(rect.left, rect.top); this.Controls.Add(comboBox.ComboBox); } } this.UpdateSize(); }
/// <summary> /// Returns a Rect containing the bounds of the specified window's area (i.e. area excluding border). /// </summary> /// <param name="hWnd">Handle of the window.</param> /// <returns>Rect containing window bounds.</returns> public static Rect GetWindowSize(IntPtr hWnd) { NativeMethods.RECT result = new NativeMethods.RECT(); if (NativeMethods.GetWindowRect(hWnd, out result)) return result; else throw new Exception(String.Format("Could not find window bounds for specified window (handle {0:X})", hWnd)); }
public static extern bool RedrawWindow(HandleRef hwnd, ref NativeMethods.RECT rcUpdate, HandleRef hrgnUpdate, int flags);
private void OnPaintThemed( PaintEventArgs e ) { NativeMethods.RECT rect = new NativeMethods.RECT(); rect.left = ClientRectangle.Left; rect.top = ClientRectangle.Top; rect.right = ClientRectangle.Right; rect.bottom = ClientRectangle.Bottom; IntPtr hdc = new IntPtr(); hdc = e.Graphics.GetHdc(); if ( BackColor.ToKnownColor() != KnownColor.Window ) { e.Graphics.ReleaseHdc( hdc ); using ( SolidBrush backgroundBrush = new SolidBrush( BackColor ) ) { e.Graphics.FillRectangle( backgroundBrush, ClientRectangle ); } hdc = e.Graphics.GetHdc(); IntPtr hTheme = NativeMethods.OpenThemeData( Handle, "Edit" ); NativeMethods.DTBGOPTS options = new NativeMethods.DTBGOPTS(); options.dwSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(options); options.dwFlags = NativeMethods.DTBG_OMITCONTENT; int state = NativeMethods.ETS_NORMAL; if ( !Enabled ) { state = NativeMethods.ETS_DISABLED; } else if ( ReadOnly ) { state = NativeMethods.ETS_READONLY; } NativeMethods.DrawThemeBackgroundEx( hTheme, hdc, NativeMethods.EP_EDITTEXT, state, ref rect, ref options ); if ( IntPtr.Zero != hTheme ) { NativeMethods.CloseThemeData( hTheme ); } } else if ( Enabled & !ReadOnly ) { IntPtr hTheme = NativeMethods.OpenThemeData( Handle, "Edit" ); NativeMethods.DrawThemeBackground( hTheme, hdc, NativeMethods.EP_EDITTEXT, NativeMethods.ETS_NORMAL, ref rect, IntPtr.Zero ); if ( IntPtr.Zero != hTheme ) { NativeMethods.CloseThemeData( hTheme ); } } else { IntPtr hTheme = NativeMethods.OpenThemeData( Handle, "Globals" ); IntPtr hBrush = NativeMethods.GetThemeSysColorBrush( hTheme, 15 ); NativeMethods.FillRect( hdc, ref rect, hBrush ); if ( IntPtr.Zero != hBrush ) { NativeMethods.DeleteObject( hBrush ); hBrush = IntPtr.Zero; } if ( IntPtr.Zero != hTheme ) { NativeMethods.CloseThemeData( hTheme ); hTheme = IntPtr.Zero; } hTheme = NativeMethods.OpenThemeData( Handle, "Edit" ); NativeMethods.DTBGOPTS options = new NativeMethods.DTBGOPTS(); options.dwSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(options); options.dwFlags = NativeMethods.DTBG_OMITCONTENT; NativeMethods.DrawThemeBackgroundEx( hTheme, hdc, NativeMethods.EP_EDITTEXT, NativeMethods.ETS_DISABLED, ref rect, ref options ); if ( IntPtr.Zero != hTheme ) { NativeMethods.CloseThemeData( hTheme ); } } e.Graphics.ReleaseHdc( hdc ); }
private void PaintThemedButtonBackground(PaintEventArgs e, Rectangle bounds, bool up) { PushButtonState pbState = DetermineState(up); // First handle transparent case if (ButtonRenderer.IsBackgroundPartiallyTransparent(pbState)) { ButtonRenderer.DrawParentBackground(e.Graphics, bounds, Control); } // Now draw the actual themed background ButtonRenderer.DrawButton(e.Graphics, Control.ClientRectangle, false, pbState); // Now overlay the background image or backcolor (the former overrides the latter), leaving a // margin. We hardcode this margin for now since GetThemeMargins returns 0 all the // time. //HACK We need to see what's best here. changing this to HACK because GetThemeMargins simply does not // work in some cases. bounds.Inflate(-buttonBorderSize, -buttonBorderSize); //only paint if the user said not to use the themed backcolor. if (!Control.UseVisualStyleBackColor) { bool painted = false; bool isHighContrastHighlighted = up && IsHighContrastHighlighted(); Color color = isHighContrastHighlighted ? SystemColors.Highlight : Control.BackColor; // Note: PaintEvent.HDC == 0 if GDI+ has used the HDC -- it wouldn't be safe for us // to use it without enough bookkeeping to negate any performance gain of using GDI. if (color.A == 255 && e.HDC != IntPtr.Zero) { if (DisplayInformation.BitsPerPixel > 8) { NativeMethods.RECT r = new NativeMethods.RECT(bounds.X, bounds.Y, bounds.Right, bounds.Bottom); // SysColorBrush does not have to be deleted. SafeNativeMethods.FillRect(new HandleRef(e, e.HDC), ref r, new HandleRef(this, isHighContrastHighlighted ? SafeNativeMethods.GetSysColorBrush(ColorTranslator.ToOle(color) & 0xFF) : Control.BackColorBrush)); painted = true; } } if (!painted) { // don't paint anything from 100% transparent background // if (color.A > 0) { if (color.A == 255) { color = e.Graphics.GetNearestColor(color); } // Color has some transparency or we have no HDC, so we must // fall back to using GDI+. // using (Brush brush = new SolidBrush(color)) { e.Graphics.FillRectangle(brush, bounds); } } } } //This code is mostly taken from the non-themed rendering code path. if (Control.BackgroundImage != null && !DisplayInformation.HighContrast) { ControlPaint.DrawBackgroundImage(e.Graphics, Control.BackgroundImage, Color.Transparent, Control.BackgroundImageLayout, Control.ClientRectangle, bounds, Control.DisplayRectangle.Location, Control.RightToLeft); } }
private void UpdateComboBoxLocation(CommandBarComboBox comboBox, int index) { NativeMethods.RECT rect = new NativeMethods.RECT(); NativeMethods.SendMessage(this.Handle, NativeMethods.TB_GETITEMRECT, index, ref rect); int height = rect.bottom - rect.top; if (height > comboBox.ComboBox.Height) { rect.top = rect.top + ((height - comboBox.ComboBox.Height) / 2); } comboBox.ComboBox.Location = new Point(rect.left + 2, rect.top); }
private void DrawTreeItem(string itemText, int imageIndex, IntPtr dc, NativeMethods.RECT rc, int state, int backColor, int textColor) { NativeMethods.SIZE size = new NativeMethods.SIZE(); NativeMethods.RECT rc2 = new NativeMethods.RECT(); ImageList imagelist = this.ImageList; IntPtr hfontOld = IntPtr.Zero; // Select the font of the dialog, so we don't get the underlined font // when the item is being tracked IntPtr fontHandle = IntPtr.Zero; if ((state & STATE_HOT) != 0) { fontHandle = Parent.Font.ToHfont(); hfontOld = NativeMethods.SelectObject(dc, fontHandle); } // Fill the background if (((state & STATE_SELECTED) != 0) && (hbrushDither != IntPtr.Zero)) { FillRectDither(dc, rc); NativeMethods.SetBkMode(dc, NativeMethods.TRANSPARENT); } else { NativeMethods.SetBkColor(dc, backColor); NativeMethods.ExtTextOut(dc, 0, 0, NativeMethods.ETO_CLIPPED | NativeMethods.ETO_OPAQUE, ref rc, null, 0, null); } // Get the height of the font NativeMethods.GetTextExtentPoint32(dc, itemText, itemText.Length, size); // Draw the caption rc2.left = rc.left + SIZE_ICON_X + 2 * PADDING_HORZ; rc2.top = rc.top + (((rc.bottom - rc.top) - size.cy) >> 1); rc2.bottom = rc2.top + size.cy; rc2.right = rc.right; NativeMethods.SetTextColor(dc, textColor); NativeMethods.DrawText(dc, itemText, itemText.Length, ref rc2, NativeMethods.DT_LEFT | NativeMethods.DT_VCENTER | NativeMethods.DT_END_ELLIPSIS | NativeMethods.DT_NOPREFIX); NativeMethods.ImageList_Draw(imagelist.Handle, imageIndex, dc, PADDING_HORZ, rc.top + (((rc.bottom - rc.top) - SIZE_ICON_Y) >> 1), NativeMethods.ILD_TRANSPARENT); // Draw the hot-tracking border if needed if ((state & STATE_HOT) != 0) { int savedColor; // top left savedColor = NativeMethods.SetBkColor(dc, ColorTranslator.ToWin32(SystemColors.ControlLightLight)); rc2.left = rc.left; rc2.top = rc.top; rc2.bottom = rc.top + 1; rc2.right = rc.right; NativeMethods.ExtTextOut(dc, 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); rc2.bottom = rc.bottom; rc2.right = rc.left + 1; NativeMethods.ExtTextOut(dc, 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); // bottom right NativeMethods.SetBkColor(dc, ColorTranslator.ToWin32(SystemColors.ControlDark)); rc2.left = rc.left; rc2.right = rc.right; rc2.top = rc.bottom - 1; rc2.bottom = rc.bottom; NativeMethods.ExtTextOut(dc, 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); rc2.left = rc.right - 1; rc2.top = rc.top; NativeMethods.ExtTextOut(dc, 0, 0, NativeMethods.ETO_OPAQUE, ref rc2, null, 0, null); NativeMethods.SetBkColor(dc, savedColor); } if (hfontOld != IntPtr.Zero) { NativeMethods.SelectObject(dc, hfontOld); } if (fontHandle != IntPtr.Zero) { NativeMethods.DeleteObject(fontHandle); } }
public void Show(Control control, Point point) { CommandBarItemCollection chevronItems = new CommandBarItemCollection(); Size size = ClientSize; for (int i = 0; i < items.Count; i++) { NativeMethods.RECT rect = new NativeMethods.RECT(); NativeMethods.SendMessage(Handle, NativeMethods.TB_GETITEMRECT, i, ref rect); if (rect.right > size.Width) { CommandBarItem item = items[i]; if (item.Visible) { if ((!(item is CommandBarSeparator)) || (chevronItems.Count != 0)) chevronItems.Add(item); } } } this.contextMenu.Mnemonics = false; this.contextMenu.Items.Clear(); this.contextMenu.Items.AddRange(chevronItems); this.contextMenu.Show(control, point); }
private void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam) { #region // old code commented out by ye.wang 2014-05-04 10:33:18 //// MINMAXINFO structure //NativeMethods.MINMAXINFO minMaxInfo = (NativeMethods.MINMAXINFO)Marshal.PtrToStructure( lParam, typeof( NativeMethods.MINMAXINFO ) ); //// Get the handle of the nearest monitor to the window ////WindowInteropHelper interopHelper = new WindowInteropHelper( this ); //IntPtr hMonitor = NativeMethods.MonitorFromWindow( _wndTarget.GetHandle(), NativeMethods.MONITOR_DEFAULTTONEAREST ); //// Get monitor information //NativeMethods.MONITORINFOEX monitorInfo = new NativeMethods.MONITORINFOEX(); //monitorInfo.cbSize = Marshal.SizeOf( monitorInfo ); //NativeMethods.GetMonitorInfo( new HandleRef( this, hMonitor ), monitorInfo ); //// Get HwndSource //HwndSource source = HwndSource.FromHwnd( _wndTarget.GetHandle() ); //if ( source == null ) // // Should never be null // throw new Exception( "Cannot get HwndSource instance." ); //if ( source.CompositionTarget == null ) // // Should never be null // throw new Exception( "Cannot get HwndTarget instance." ); //// Get working area rectangle //NativeMethods.RECT workingArea = monitorInfo.rcWork; //Console.WriteLine( string.Format( "left:{0},top:{1},right:{2},bottom:{3}", monitorInfo.rcWork.Left, // monitorInfo.rcWork.Top, monitorInfo.rcWork.Right, monitorInfo.rcWork.Bottom ) ); //// Get transformation matrix //System.Windows.Media.Matrix matrix = source.CompositionTarget.TransformFromDevice; //// Convert working area rectangle to DPI-independent values //Point convertedSize = // matrix.Transform( new Point( // workingArea.Right - workingArea.Left, // workingArea.Bottom - workingArea.Top // ) ); //Point convertedPosion = // matrix.Transform( new Point( // workingArea.Left, workingArea.Top // ) ); //// Set the maximized size of the window //minMaxInfo.ptMaxSize.X = (int)convertedSize.X+6; //minMaxInfo.ptMaxSize.Y = (int)convertedSize.Y+6; //// Set the position of the maximized window //minMaxInfo.ptMaxPosition.X = (int)convertedPosion.X-WND_BORDER_DROPSHADOW_SIZE; //minMaxInfo.ptMaxPosition.Y = (int)convertedPosion.Y-WND_BORDER_DROPSHADOW_SIZE; //Console.WriteLine( string.Format( "MaxInfo : left:{0},top:{1},right:{2},bottom:{3}", // convertedPosion.X, convertedPosion.Y, convertedSize.X, convertedSize.Y ) ); //Marshal.StructureToPtr( minMaxInfo, lParam, true ); #endregion // // old code NativeMethods.MINMAXINFO mmi = (NativeMethods.MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(NativeMethods.MINMAXINFO)); IntPtr monitor = NativeMethods.MonitorFromWindow(hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST); if (monitor != IntPtr.Zero) { NativeMethods.MONITORINFOEX monitorInfo = new NativeMethods.MONITORINFOEX(); monitorInfo.cbSize = Marshal.SizeOf(monitorInfo); NativeMethods.GetMonitorInfo(new HandleRef(this, monitor), monitorInfo); NativeMethods.RECT rcWorkArea = monitorInfo.rcWork; NativeMethods.RECT rcMonitorArea = monitorInfo.rcMonitor; //mmi.ptMaxPosition.X = ( null != this.MaxiX ? this.MaxiX.Value : Math.Abs( rcWorkArea.Left - rcMonitorArea.Left ) ) - WND_BORDER_DROPSHADOW_SIZE; //mmi.ptMaxPosition.Y = ( null != this.MaxiY ? this.MaxiY.Value : Math.Abs( rcWorkArea.Top - rcMonitorArea.Top ) ) - WND_BORDER_DROPSHADOW_SIZE; if (!_bUseCall) { // use field mmi.ptMaxPosition.X = (null != this._maxiX ? this._maxiX.Value : Math.Abs(rcWorkArea.Left - rcMonitorArea.Left)) - WND_BORDER_DROPSHADOW_SIZE; mmi.ptMaxPosition.Y = (null != this._maxiY ? this._maxiY.Value : Math.Abs(rcWorkArea.Top - rcMonitorArea.Top)) - WND_BORDER_DROPSHADOW_SIZE; } else { if (null == this._maxiX_call) { this._maxiX_call = () => null; } if (null == this._maxiY_call) { this._maxiY_call = () => null; } int?ret_x = this._maxiX_call.Invoke(); int?ret_y = this._maxiY_call.Invoke(); mmi.ptMaxPosition.X = (null != ret_x ? ret_x.Value : Math.Abs(rcWorkArea.Left - rcMonitorArea.Left)) - WND_BORDER_DROPSHADOW_SIZE; mmi.ptMaxPosition.Y = (null != ret_y ? ret_y.Value : Math.Abs(rcWorkArea.Top - rcMonitorArea.Top)) - WND_BORDER_DROPSHADOW_SIZE; } mmi.ptMaxSize.X = Math.Abs( Math.Abs(rcWorkArea.Right - rcWorkArea.Left) + WND_BORDER_DROPSHADOW_SIZE - mmi.ptMaxPosition.X); mmi.ptMaxSize.Y = Math.Abs( Math.Abs(rcWorkArea.Bottom - rcWorkArea.Top) + WND_BORDER_DROPSHADOW_SIZE - mmi.ptMaxPosition.Y); mmi.ptMinTrackSize.X = (int)this._wndTarget.MinWidth; mmi.ptMinTrackSize.Y = (int)this._wndTarget.MinHeight; } Marshal.StructureToPtr(mmi, lParam, true); }
private void TrackDropDown(int index) { while (index >= 0) { this.trackNextItem = -1; this.BeginUpdate(); CommandBarMenu menu = this.items[index] as CommandBarMenu; if (menu != null) { menu.PerformDropDown(EventArgs.Empty); this.contextMenu.Items.Clear(); this.contextMenu.Items.AddRange(menu.Items); // = menu.Items; this.contextMenu.Mnemonics = true; } else { this.contextMenu.Items.Clear(); // .Items = new CommandBarItemCollection(); this.contextMenu.Mnemonics = true; } // Item state NativeMethods.SendMessage(this.Handle, NativeMethods.TB_PRESSBUTTON, index, -1); // Trick to get the first menu item selected NativeMethods.PostMessage(this.Handle, NativeMethods.WM_KEYDOWN, (int) Keys.Down, 1); NativeMethods.PostMessage(this.Handle, NativeMethods.WM_KEYUP, (int) Keys.Down, 1); this.SetState(State.HotTracking, index); // Hook NativeMethods.HookProc hookProc = new NativeMethods.HookProc(DropDownHook); GCHandle hookProcHandle = GCHandle.Alloc(hookProc); this.hookHandle = NativeMethods.SetWindowsHookEx(NativeMethods.WH_MSGFILTER, hookProc, IntPtr.Zero, NativeMethods.GetCurrentThreadId()); if (this.hookHandle == IntPtr.Zero) { throw new SecurityException(); } // Ask for position NativeMethods.RECT rect = new NativeMethods.RECT(); NativeMethods.SendMessage(Handle, NativeMethods.TB_GETRECT, index, ref rect); Point position = new Point(rect.left, rect.bottom); this.EndUpdate(); this.Update(); this.contextMenu.Show(this, position); // Unhook NativeMethods.UnhookWindowsHookEx(hookHandle); hookProcHandle.Free(); this.hookHandle = IntPtr.Zero; // Item state NativeMethods.SendMessage(Handle, NativeMethods.TB_PRESSBUTTON, index, 0); this.SetState(trackEscapePressed ? State.Hot : State.None, index); index = trackNextItem; } }
public int GetClientHeight() { NativeMethods.RECT rect = new NativeMethods.RECT(); GetClientRect(hr, ref rect); return(rect.bottom); }
internal void MoveToScreenCenter(HandleRef hWnd) { // Create an IntPtr to store a handle to the monitor. IntPtr hMonitor = IntPtr.Zero; // Get the monitor to use based on the location of the parent window if (_hwndOwnerWindow != IntPtr.Zero) { // we have a owner hwnd; center on the screen on // which our owner hwnd is. // We use MONITOR_DEFAULTTONEAREST to get the monitor // nearest to the window if the window doesn't intersect // any display monitor. hMonitor = SafeNativeMethods.MonitorFromWindow( new HandleRef(this, _hwndOwnerWindow), // window to find monitor location for NativeMethods.MONITOR_DEFAULTTONEAREST); // get the monitor nearest to the window // Only move the window if we got a valid monitor... otherwise let Windows // position the dialog. if (hMonitor != IntPtr.Zero) { // Now, create another RECT and fill it with the bounds of the parent window. NativeMethods.RECT dialogRect = new NativeMethods.RECT(); SafeNativeMethods.GetWindowRect(hWnd, ref dialogRect); Size dialogSize = new Size((dialogRect.right - dialogRect.left), /*width*/ (dialogRect.bottom - dialogRect.top)); /*height*/ // create variables that will receive the new position of the dialog double x = 0; double y = 0; // Call into a static function in System.Windows.Window to calculate // the actual new position Window.CalculateCenterScreenPosition( hMonitor, dialogSize, ref x, ref y); // Call SetWindowPos to actually move the window. UnsafeNativeMethods.SetWindowPos(hWnd, // handle to the window to move NativeMethods.NullHandleRef, // window to precede this one in zorder (int)Math.Round(x), (int)Math.Round(y), // new X and Y positions 0, 0, // new width and height, if applicable // Flags: // SWP_NOSIZE: Retains current size // SWP_NOZORDER: retains current zorder // SWP_NOACTIVATE: does not activate the window NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); } } }
public static extern bool GetClientRect(HandleRef hWnd, [In, Out] ref NativeMethods.RECT rect);