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>
        /// 解析。
        /// </summary>
        /// <param name="handle">ハンドル。</param>
        /// <param name="analyzer">別システムウィンドウ解析。</param>
        /// <returns>解析結果。</returns>
        public static WindowInfo Analyze(IntPtr handle, IOtherSystemWindowAnalyzer[] analyzer)
        {
            //子ウィンドウを全て取得する
            List<IntPtr> children = new List<IntPtr>();
            NativeMethods.EnumWindowsDelegate callback = delegate(IntPtr hWnd, IntPtr lParam)
            {
                children.Add(hWnd);
                return 1;
            };
            NativeMethods.EnumChildWindows(handle, callback, IntPtr.Zero);
            GC.KeepAlive(callback);

            //ウィンドウ情報を取得する
            WindowInfo info = new WindowInfo();
            info.Handle = handle;
            NativeMethods.RECT rc = new NativeMethods.RECT();
            NativeMethods.GetWindowRect(handle, ref rc);
            List<int> zIndex = new List<int>();
            GetWindowInfo(new Point(rc.left, rc.top), info, children, zIndex, analyzer);
            return info;
        }
Esempio n. 3
0
 public static extern bool DrawFrameControl(HandleRef hDC, ref NativeMethods.RECT rect, int type, int state);
Esempio n. 4
0
            // move the bars to their respective positions
            public IntPtr PositionBars(IntPtr winPosInfo, IEnumerable<IBar> bars)
            {
                this.bars = bars;

                var topBar = edge == NativeMethods.ABE.ABE_TOP;
                var currentY = topBar ? rect.top : rect.bottom;
                foreach (var bar in bars)
                {
                    if (!topBar)
                    {
                        currentY -= bar.GetBarHeight();
                    }
                    var barRect = new NativeMethods.RECT
                        {
                            left = rect.left,
                            top = currentY,
                            right = rect.right,
                            bottom = currentY + bar.GetBarHeight()
                        };
                    if (topBar)
                    {
                        currentY += bar.GetBarHeight();
                    }

                    bar.OnClientWidthChanging(barRect.right - barRect.left);

                    NativeMethods.AdjustWindowRectEx(ref barRect, NativeMethods.GetWindowStyleLongPtr(bar.Handle),
                        NativeMethods.GetMenu(bar.Handle) != IntPtr.Zero, NativeMethods.GetWindowExStyleLongPtr(bar.Handle));

                    winPosInfo = NativeMethods.DeferWindowPos(winPosInfo, bar.Handle, NativeMethods.HWND_TOPMOST, barRect.left, barRect.top,
                        barRect.right - barRect.left, barRect.bottom - barRect.top, NativeMethods.SWP.SWP_NOACTIVATE);
                }

                isTopMost = true;

                return winPosInfo;
            }
Esempio n. 5
0
 public static extern bool InvalidateRect(HandleRef hWnd, ref NativeMethods.RECT rect, bool erase);
Esempio n. 6
0
 public static extern bool ScrollWindow(HandleRef hWnd, int nXAmount, int nYAmount, ref NativeMethods.RECT rectScrollRegion, ref NativeMethods.RECT rectClip);
Esempio n. 7
0
		public static extern bool GetWindowRect(IntPtr hWnd, out NativeMethods.RECT lpRect);
Esempio n. 8
0
 public static extern bool LPtoDP(HandleRef hDC, [In, Out] ref NativeMethods.RECT lpRect, int nCount);
Esempio n. 9
0
		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 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 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;
                Color color = 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);
                        SafeNativeMethods.FillRect(new HandleRef(e, e.HDC), ref r, new HandleRef(this, 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);
            }
        }
Esempio n. 12
0
        /// <summary>
        ///  Sets all the properties for this panel.
        /// </summary>
        internal void Realize()
        {
            if (Created)
            {
                string text;
                string sendText;
                int    border = 0;

                if (this.text == null)
                {
                    text = string.Empty;
                }
                else
                {
                    text = this.text;
                }

                HorizontalAlignment align = alignment;
                // Translate the alignment for Rtl apps
                //
                if (parent.RightToLeft == RightToLeft.Yes)
                {
                    switch (align)
                    {
                    case HorizontalAlignment.Left:
                        align = HorizontalAlignment.Right;
                        break;

                    case HorizontalAlignment.Right:
                        align = HorizontalAlignment.Left;
                        break;
                    }
                }

                switch (align)
                {
                case HorizontalAlignment.Center:
                    sendText = "\t" + text;
                    break;

                case HorizontalAlignment.Right:
                    sendText = "\t\t" + text;
                    break;

                default:
                    sendText = text;
                    break;
                }
                switch (borderStyle)
                {
                case StatusBarPanelBorderStyle.None:
                    border |= NativeMethods.SBT_NOBORDERS;
                    break;

                case StatusBarPanelBorderStyle.Sunken:
                    break;

                case StatusBarPanelBorderStyle.Raised:
                    border |= NativeMethods.SBT_POPOUT;
                    break;
                }
                switch (style)
                {
                case StatusBarPanelStyle.Text:
                    break;

                case StatusBarPanelStyle.OwnerDraw:
                    border |= NativeMethods.SBT_OWNERDRAW;
                    break;
                }

                int wparam = GetIndex() | border;
                if (parent.RightToLeft == RightToLeft.Yes)
                {
                    wparam |= NativeMethods.SBT_RTLREADING;
                }

                int result = (int)UnsafeNativeMethods.SendMessage(new HandleRef(parent, parent.Handle), NativeMethods.SB_SETTEXT, (IntPtr)wparam, sendText);

                if (result == 0)
                {
                    throw new InvalidOperationException(SR.UnableToSetPanelText);
                }

                if (icon != null && style != StatusBarPanelStyle.OwnerDraw)
                {
                    parent.SendMessage(NativeMethods.SB_SETICON, (IntPtr)GetIndex(), icon.Handle);
                }
                else
                {
                    parent.SendMessage(NativeMethods.SB_SETICON, (IntPtr)GetIndex(), IntPtr.Zero);
                }

                if (style == StatusBarPanelStyle.OwnerDraw)
                {
                    NativeMethods.RECT rect = new NativeMethods.RECT();
                    result = (int)UnsafeNativeMethods.SendMessage(new HandleRef(parent, parent.Handle), NativeMethods.SB_GETRECT, (IntPtr)GetIndex(), ref rect);

                    if (result != 0)
                    {
                        parent.Invalidate(Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom));
                    }
                }
            }
        }
Esempio n. 13
0
        private void ClipCursor(bool reset)
        {
            Rectangle rect;
            if (reset)
            {
                rect = Screen.GetBounds(this);
            }
            else
            {
                rect = SelectImageRect;
            }

            NativeMethods.RECT nativeRect = new NativeMethods.RECT(rect);
            NativeMethods.ClipCursor(ref nativeRect);
        }
Esempio n. 14
0
		/// <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);
		}
Esempio n. 15
0
		public static extern int DrawThemeBackground(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, ref NativeMethods.RECT pRect, ref NativeMethods.RECT pClipRect);
Esempio n. 16
0
		public static extern int DrawThemeParentBackground(IntPtr hWnd, IntPtr hdc, ref NativeMethods.RECT pRect);
Esempio n. 17
0
		public static extern int GetThemeBackgroundContentRect(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, ref NativeMethods.RECT pBoundingRect, out NativeMethods.RECT pContentRect);
Esempio n. 18
0
        private void PaintNonClientRegion(ref Message m)
        {
            IntPtr handle = Handle;

            NativeMethods.RECT windowRect;
            NativeMethods.GetWindowRect(handle, out windowRect);
            windowRect = new NativeMethods.RECT(
                0,
                0,
                windowRect.Right - windowRect.Left,
                windowRect.Bottom - windowRect.Top);

            using (var deviceContext = new NativeMethods.DeviceContext(handle))
            {
                var renderer = new VisualStyleRenderer(
                    Enabled
                        ? ReadOnly
                            ? VisualStyleElement.TextBox.TextEdit.ReadOnly
                            : VisualStyleElement.TextBox.TextEdit.Normal
                        : VisualStyleElement.TextBox.TextEdit.Disabled);

                int clipResult =
                    NativeMethods.ExcludeClipRect(
                        deviceContext.GetHdc(),
                        _borderRect.Left,
                        _borderRect.Top,
                        windowRect.Right - _borderRect.Right,
                        windowRect.Bottom - _borderRect.Bottom);

                if (clipResult == NativeMethods.SIMPLEREGION
                    || clipResult == NativeMethods.COMPLEXREGION)
                {
                    if (renderer.IsBackgroundPartiallyTransparent())
                        renderer.DrawParentBackground(deviceContext, windowRect.ToRectangle(), this);

                    renderer.DrawBackground(deviceContext, windowRect.ToRectangle());
                }
            }

            m.Result = IntPtr.Zero;
        }
        private Size MeassureTextInternal(string text)
        {
            NativeMethods.RECT rect = new NativeMethods.RECT();
            rect.left = 0;
            rect.right = 0;
            rect.top = 0;
            rect.bottom = 0;

            // ExtTextOut does not show Mnemonics highlighting.
            NativeMethods.DrawText(this.graphicsHandle, text, text.Length, ref rect, NativeMethods.DT_SINGLELINE | NativeMethods.DT_LEFT | NativeMethods.DT_CALCRECT);

            return new Size(rect.right, rect.bottom);
        }
Esempio n. 20
0
		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;
			}
		}				
		/// <summary>
        /// ウィンドウ情報取得。
		/// </summary>
        /// <param name="pos">ルートウィンドウの左上座標。</param>
        /// <param name="info">ウィンドウ情報格納バッファ。</param>
        /// <param name="children">子ウィンドウハンドル。</param>
        /// <param name="analyzer">別システムウィンドウ解析。</param>
        /// <param name="zIndex">Zインデックス。</param>
        private static void GetWindowInfo(Point pos, WindowInfo info, List<IntPtr> children, List<int> zIndex, IOtherSystemWindowAnalyzer[] analyzer)
		{
			NativeMethods.RECT rc = new NativeMethods.RECT();
			NativeMethods.GetWindowRect(info.Handle, ref rc);
			info.Bounds = new Rectangle(rc.left - pos.X, rc.top - pos.Y, rc.right - rc.left, rc.bottom - rc.top);

			//ウィンドウテキスト取得
            int len = NativeMethods.GetWindowTextLength(info.Handle);
            StringBuilder builder = new StringBuilder((len + 1) * 8);
			NativeMethods.GetWindowText(info.Handle, builder, len * 8);
			info.Text = builder.ToString();
			
			//z順設定
			info.ZIndex = zIndex.ToArray();

			//ダイアログID取得
			info.DialogId = NativeMethods.GetDlgCtrlID(info.Handle);

			//ウィンドウクラス名称取得
			StringBuilder className = new StringBuilder((WindowClassNameMax + 1) * 8);
			NativeMethods.GetClassName(info.Handle, className, WindowClassNameMax * 8);
			info.ClassName = className.ToString();

            //他のウィンドウシステムのウィンドウの場合は解析処理を委譲
            List<WindowInfo> otherSystemChildren = new List<WindowInfo>();
            for (int i = 0; i < analyzer.Length; i++)
            {
                WindowInfo obj = analyzer[i].Analyze(info.Handle);
                if (obj != null)
                {
                    info.TypeFullName = obj.TypeFullName;
                    info.TargetObject = obj.TargetObject;
                    otherSystemChildren.AddRange(obj.Children);
                    break;
                }
            }
            if (info.TargetObject == null)
            {
                //.Netのコントロールの場合、型を取得する
                Control net = Control.FromHandle(info.Handle);
                if (net != null)
                {
                    info.TypeFullName = net.GetType().FullName;
                    info.TargetObject = net;
                }
            }

			//自分の子ウィンドウを集める
			List<IntPtr> myChildren = new List<IntPtr>();
			for (int i = children.Count - 1; 0 <= i; i--)
			{
				if (NativeMethods.GetParent(children[i]) == info.Handle)
				{
					myChildren.Add(children[i]);
					children.RemoveAt(i);
				}
			}

			//Z順でソートする
			IntPtr[] myChildrenSort = WindowPositionUtility.SortByZIndex(myChildren.ToArray());

			//子のウィンドウ情報を設定する
			zIndex.Add(0);
            List<WindowInfo> allChildren = new List<WindowInfo>();
            for (int i = 0; i < myChildrenSort.Length; i++)
			{
				zIndex[zIndex.Count - 1] = i;
				WindowInfo c = new WindowInfo();
				c.Handle = myChildrenSort[i];
                allChildren.Add(c);
				GetWindowInfo(pos, c, children, zIndex, analyzer);
			}
			zIndex.RemoveAt(zIndex.Count - 1);
            
            //別システムに属するウィンドウはZIndexの整合性が取れなくなるので最後に追加
            allChildren.AddRange(otherSystemChildren);
            info.Children = allChildren.ToArray();
		}
 /// <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));
 }
Esempio n. 23
0
        private NativeMethods.RECT CalculateFrameSize(int x, int y, int cx, int cy)
        {
            NativeMethods.RECT windowRect = new NativeMethods.RECT(x, y, x + cx, y + cy);
            // subtract original frame size
            windowRect.Left -= _iFrameWidth;
            windowRect.Right += _iFrameWidth;
            windowRect.Top -= _iCaptionHeight;
            windowRect.Bottom += _iFrameHeight;
            // reset client area with new size
            windowRect.Left += ParentForm.BorderSize;
            windowRect.Right -= ParentForm.BorderSize;
            windowRect.Bottom -= ParentForm.BorderSize;
            windowRect.Top += ParentForm.BorderSize;

            NativeMethods.RECT clientRect = new NativeMethods.RECT(windowRect.Left, windowRect.Top, windowRect.Right, windowRect.Bottom);

            return windowRect;
        }
Esempio n. 24
0
 public static extern int FillRect(HandleRef hdc, [In] ref NativeMethods.RECT rect, HandleRef hbrush);
Esempio n. 25
0
        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);
                        }
                    }

                }
            }
            finally
            {
                NativeMethods.ExcludeClipRect(hDC, -borderSize, -borderSize, clientRect.Right + borderSize, clientRect.Bottom + borderSize);
                NativeMethods.ReleaseDC(FormHandle, hDC);
            }
        }
Esempio n. 26
0
 public static extern bool RedrawWindow(HandleRef hwnd, ref NativeMethods.RECT rcUpdate, HandleRef hrgnUpdate, int flags);
        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;
            }
        }
Esempio n. 28
0
 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);
Esempio n. 29
0
 public int GetClientHeight()
 {
     NativeMethods.RECT rect = new NativeMethods.RECT();
     GetClientRect(hr, ref rect);
     return rect.bottom;
 }
Esempio n. 30
0
 public static extern bool DrawEdge(HandleRef hDC, ref NativeMethods.RECT rect, int edge, int flags);
Esempio n. 31
0
 public int IndexFromPoint(int x, int y)
 {
     NativeMethods.RECT rect = new NativeMethods.RECT();
     GetClientRect(hr, ref rect);
     if (((rect.left <= x) && (x < rect.right)) && ((rect.top <= y) && (y < rect.bottom)))
     {
         int n = (int)SendMessage(hr, 0x1a9, 0, (int)MAKELPARAM(x, y));
         if (HIWORD(n) == 0)
         {
             return LOWORD(n);
         }
     }
     return -1;
 }
Esempio n. 32
0
 public static extern int GetRgnBox(HandleRef hRegion, ref NativeMethods.RECT clipRect);
Esempio n. 33
0
      protected override void  WndProc(ref Message m)            {                
          if ((m.Msg == NativeMethods.WM_NCHITTEST) && SizingGrip) {
            // if we're within the grip bounds tell windows
            // that we're the bottom right of the window.  
            Rectangle sizeGripBounds = SizeGripBounds;
            int x = NativeMethods.Util.LOWORD(m.LParam);
            int y = NativeMethods.Util.HIWORD(m.LParam);

                       
            if (sizeGripBounds.Contains(PointToClient(new Point(x, y)))) {
                HandleRef rootHwnd = WindowsFormsUtils.GetRootHWnd(this);

                // if the main window isnt maximized - we should paint a resize grip.
                // double check that we're at the bottom right hand corner of the window.
                if (rootHwnd.Handle != IntPtr.Zero && !UnsafeNativeMethods.IsZoomed(rootHwnd)) {
                    // get the client area of the topmost window.  If we're next to the edge then 
                    // the sizing grip is valid.
                    NativeMethods.RECT rootHwndClientArea = new NativeMethods.RECT();
                    UnsafeNativeMethods.GetClientRect(rootHwnd, ref rootHwndClientArea);
                    
                    // map the size grip FROM statusStrip coords TO the toplevel window coords.
                    NativeMethods.POINT gripLocation;
                    if (RightToLeft == RightToLeft.Yes) {
                        gripLocation = new NativeMethods.POINT(SizeGripBounds.Left, SizeGripBounds.Bottom);
                    }
                    else {
                        gripLocation = new NativeMethods.POINT(SizeGripBounds.Right, SizeGripBounds.Bottom);
                    }
                    UnsafeNativeMethods.MapWindowPoints(new HandleRef(this, this.Handle), rootHwnd, gripLocation, 1);

                    int deltaBottomEdge = Math.Abs(rootHwndClientArea.bottom - gripLocation.y);
                    int deltaRightEdge = Math.Abs(rootHwndClientArea.right - gripLocation.x);
                    
                    if (RightToLeft != RightToLeft.Yes) {
                        if ((deltaRightEdge + deltaBottomEdge) < 2) {
                            m.Result = (IntPtr)NativeMethods.HTBOTTOMRIGHT;                   
                            return;                      
                        }
                    }
                    
                    
                }
               
            }                
          }
          base.WndProc(ref m);            
       }
Esempio n. 34
0
            public bool SetPosition(Monitor monitor)
            {
                this.monitor = monitor;

                var appBarData = new NativeMethods.APPBARDATA(this.Handle, uEdge: edge, rc: new NativeMethods.RECT { left = monitor.Bounds.Left, right = monitor.Bounds.Right });

                if (edge == NativeMethods.ABE.ABE_TOP)
                {
                    appBarData.rc.top = monitor.Bounds.Top;
                    appBarData.rc.bottom = appBarData.rc.top + this.height;
                }
                else
                {
                    appBarData.rc.bottom = monitor.Bounds.Bottom;
                    appBarData.rc.top = appBarData.rc.bottom - this.height;
                }

                NativeMethods.SHAppBarMessage(NativeMethods.ABM.ABM_QUERYPOS, ref appBarData);

                if (edge == NativeMethods.ABE.ABE_TOP)
                {
                    appBarData.rc.bottom = appBarData.rc.top + this.height;
                }
                else
                {
                    appBarData.rc.top = appBarData.rc.bottom - this.height;
                }

                NativeMethods.SHAppBarMessage(NativeMethods.ABM.ABM_SETPOS, ref appBarData);

                var changedPosition = appBarData.rc.bottom != rect.bottom || appBarData.rc.top != rect.top ||
                    appBarData.rc.left != rect.left || appBarData.rc.right != rect.right;

                this.rect = appBarData.rc;

                this.visible = true;

                return changedPosition;
            }
Esempio n. 35
0
            public DCMapping(HandleRef hDC, Rectangle bounds)
            {
                if (hDC.Handle == IntPtr.Zero)
                {
                    throw new ArgumentNullException("hDC");
                }

                bool success;

                NativeMethods.POINT viewportOrg             = new NativeMethods.POINT();
                HandleRef           hOriginalClippingRegion = NativeMethods.NullHandleRef;

                NativeMethods.RegionFlags originalRegionType = NativeMethods.RegionFlags.NULLREGION;

                this.translatedBounds = bounds;
                this.graphics         = null;
                this.dc = DeviceContext.FromHdc(hDC.Handle);

                this.dc.SaveHdc();

                // Retrieve the x-coordinates and y-coordinates of the viewport origin for the specified device context.
                success = SafeNativeMethods.GetViewportOrgEx(hDC, viewportOrg);
                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.
                HandleRef hClippingRegion = new HandleRef(null, SafeNativeMethods.CreateRectRgn(viewportOrg.x + bounds.Left, viewportOrg.y + bounds.Top, viewportOrg.x + bounds.Right, viewportOrg.y + bounds.Bottom));

                Debug.Assert(hClippingRegion.Handle != 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 = new HandleRef(this, SafeNativeMethods.CreateRectRgn(0, 0, 0, 0));
                    Debug.Assert(hOriginalClippingRegion.Handle != IntPtr.Zero, "CreateRectRgn() failed.");

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

                    // Shift the viewpoint origint by coordinates specified in "bounds".
                    NativeMethods.POINT lastViewPort = new NativeMethods.POINT();
                    success = SafeNativeMethods.SetViewportOrgEx(hDC, viewportOrg.x + bounds.Left, viewportOrg.y + bounds.Top, lastViewPort);
                    Debug.Assert(success, "SetViewportOrgEx() failed.");

                    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.)
                        NativeMethods.RECT originalClipRect = new NativeMethods.RECT();
                        originalRegionType = (NativeMethods.RegionFlags)SafeNativeMethods.GetRgnBox(hOriginalClippingRegion, ref originalClipRect);
                        Debug.Assert(originalRegionType != NativeMethods.RegionFlags.ERROR, "ERROR returned from SelectClipRgn while selecting the original clipping region..");

                        if (originalRegionType == NativeMethods.RegionFlags.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
                            NativeMethods.RegionFlags combineResult = (NativeMethods.RegionFlags)SafeNativeMethods.CombineRgn(hClippingRegion, hClippingRegion, hOriginalClippingRegion, NativeMethods.RGN_AND);
                            Debug.Assert((combineResult == NativeMethods.RegionFlags.SIMPLEREGION) ||
                                         (combineResult == NativeMethods.RegionFlags.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.
                        SafeNativeMethods.DeleteObject(hOriginalClippingRegion);
                        hOriginalClippingRegion = new HandleRef(null, IntPtr.Zero);
                        originalRegionType      = NativeMethods.RegionFlags.SIMPLEREGION;
                    }

                    // Select the new clipping region; make sure it's a SIMPLEREGION or NULLREGION
                    NativeMethods.RegionFlags selectResult = (NativeMethods.RegionFlags)SafeNativeMethods.SelectClipRgn(hDC, hClippingRegion);
                    Debug.Assert((selectResult == NativeMethods.RegionFlags.SIMPLEREGION ||
                                  selectResult == NativeMethods.RegionFlags.NULLREGION),
                                 "SIMPLEREGION or NULLLREGION expected.");
                }
                catch (Exception ex)
                {
                    if (ClientUtils.IsSecurityOrCriticalException(ex))
                    {
                        throw;
                    }

                    this.dc.RestoreHdc();
                    this.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 = SafeNativeMethods.DeleteObject(hClippingRegion);
                    Debug.Assert(success, "DeleteObject(hClippingRegion) failed.");

                    if (hOriginalClippingRegion.Handle != IntPtr.Zero)
                    {
                        success = SafeNativeMethods.DeleteObject(hOriginalClippingRegion);
                        Debug.Assert(success, "DeleteObject(hOriginalClippingRegion) failed.");
                    }
                }
            }
Esempio n. 36
0
        private void CalculateNonClientSize(ref Message m)
        {
            NativeMethods.NCCALCSIZE_PARAMS parameters;
            NativeMethods.RECT windowRect;

            ExtractParamsAndWindowRect(ref m, out parameters, out windowRect);
            var renderer = new VisualStyleRenderer(VisualStyleElement.TextBox.TextEdit.Normal);

            using (var deviceContext = new NativeMethods.DeviceContext(Handle))
            {
                var contentRect = new NativeMethods.RECT(
                    renderer.GetBackgroundContentRectangle(deviceContext, windowRect.ToRectangle()));
                contentRect.Inflate(-1, -1);

                _borderRect = new NativeMethods.RECT(
                    contentRect.Left - windowRect.Left,
                    contentRect.Top - windowRect.Top,
                    windowRect.Right - contentRect.Right,
                    windowRect.Bottom - contentRect.Bottom);

                if (m.WParam == IntPtr.Zero)
                    Marshal.StructureToPtr(contentRect, m.LParam, false);
                else
                {
                    parameters.rgrc0 = contentRect;
                    Marshal.StructureToPtr(parameters, m.LParam, false);
                }
            }

            m.Result = new IntPtr(NativeMethods.WVR_REDRAW);
        }
Esempio n. 37
0
 public static extern IntPtr MonitorFromRect(ref NativeMethods.RECT rect, int flags);
        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);
        }
Esempio n. 39
0
 public extern static bool GetClipCursor([In, Out] ref NativeMethods.RECT lpRect);
Esempio n. 40
0
		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;
			}

			this.Size = size;
		}
Esempio n. 41
0
 public static extern bool AdjustWindowRectExForDpi(ref NativeMethods.RECT lpRect, int dwStyle, bool bMenu, int dwExStyle, uint dpi);
Esempio n. 42
0
		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.IsVisible) 
					{
						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);
		}
Esempio n. 43
0
 public static extern bool GetClientRect(HandleRef hWnd, [In, Out] ref NativeMethods.RECT rect);
        /// <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
            FieldInfo windowFieldInfo = notifyicon.GetType().GetField("window", BindingFlags.NonPublic | BindingFlags.Instance);
            System.Windows.Forms.NativeWindow nativeWindow = (System.Windows.Forms.NativeWindow)windowFieldInfo.GetValue(notifyicon);
            IntPtr iconhandle = nativeWindow.Handle;
            if (iconhandle == null || iconhandle == IntPtr.Zero)
                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;
        }
Esempio n. 45
0
 public static extern bool ValidateRect(HandleRef hWnd, [In, Out] ref NativeMethods.RECT rect);
Esempio n. 46
0
        public unsafe static NativeMethods.RECT[] GetRectsFromRegion(IntPtr hRgn) {
            NativeMethods.RECT[] regionRects = null;
            IntPtr pBytes = IntPtr.Zero;
            try {
                // see how much memory we need to allocate
                int regionDataSize = GetRegionData(new HandleRef(null, hRgn), 0, IntPtr.Zero);
                if (regionDataSize != 0) {
                    pBytes = Marshal.AllocCoTaskMem(regionDataSize);
                    // get the data
                    int ret = GetRegionData(new HandleRef(null, hRgn), regionDataSize, pBytes);
                    if (ret == regionDataSize) {
                        // cast to the structure
                        NativeMethods.RGNDATAHEADER* pRgnDataHeader = (NativeMethods.RGNDATAHEADER*)pBytes;
                        if (pRgnDataHeader->iType == 1) {    // expecting RDH_RECTANGLES
                            regionRects = new NativeMethods.RECT[pRgnDataHeader->nCount];

                            Debug.Assert(regionDataSize == pRgnDataHeader->cbSizeOfStruct + pRgnDataHeader->nCount * pRgnDataHeader->nRgnSize);
                            Debug.Assert(Marshal.SizeOf(typeof(NativeMethods.RECT)) == pRgnDataHeader->nRgnSize || pRgnDataHeader->nRgnSize == 0);

                            // use the header size as the offset, and cast each rect in.
                            int rectStart = pRgnDataHeader->cbSizeOfStruct;
                            for (int i = 0; i < pRgnDataHeader->nCount; i++) {
                                // use some fancy pointer math to just copy the rect bits directly into the array.
                                regionRects[i] = *((NativeMethods.RECT*)((byte*)pBytes + rectStart + (Marshal.SizeOf(typeof(NativeMethods.RECT)) * i)));
                            }
                        }
                    }
                }
            }
            finally {
                if (pBytes != IntPtr.Zero) {
                    Marshal.FreeCoTaskMem(pBytes);
                }
            }
            return regionRects;
        }
Esempio n. 47
0
            public System.IntPtr CbtHookProc(int nCode, System.IntPtr wParam, System.IntPtr lParam)
            {
                switch (nCode) {
                    case NativeMethods.HCBT_ACTIVATE:
                        System.Diagnostics.Debug.WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, "I: Dialog HCBT_ACTIVATE (hWnd={0}).    {{Medo.MessageBox}}", wParam.ToString()));

                        if (this._owner != null) {
                            NativeMethods.RECT rectMessage = new NativeMethods.RECT();
                            NativeMethods.RECT rectOwner = new NativeMethods.RECT();
                            if ((NativeMethods.GetWindowRect(wParam, ref rectMessage)) && (NativeMethods.GetWindowRect(this._owner.Handle, ref rectOwner))) {
                                int widthMessage = rectMessage.right - rectMessage.left;
                                int heightMessage = rectMessage.bottom - rectMessage.top;
                                int widthOwner = rectOwner.right - rectOwner.left;
                                int heightOwner = rectOwner.bottom - rectOwner.top;

                                int newLeft = rectOwner.left + (widthOwner - widthMessage) / 2;
                                int newTop = rectOwner.top + (heightOwner - heightMessage) / 2;

                                NativeMethods.SetWindowPos(wParam, System.IntPtr.Zero, newLeft, newTop, 0, 0, NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE);
                            }
                        }

                        if (Resources.IsTranslatable) {
                            NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_OK, Resources.OK);
                            NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_CANCEL, Resources.Cancel);
                            NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_ABORT, Resources.Abort);
                            NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_RETRY, Resources.Retry);
                            NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_IGNORE, Resources.Ignore);
                            NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_YES, Resources.Yes);
                            NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_NO, Resources.No);
                        }

                        try {
                            return NativeMethods.CallNextHookEx(this._hook, nCode, wParam, lParam);
                        } finally {
                            this.Dispose();
                        }
                }
                return NativeMethods.CallNextHookEx(this._hook, nCode, wParam, lParam);
            }