c# 停靠窗体
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public partial class FrmAnchor : Form, IMessageFilter { public FrmAnchor(Control parentControlc, Control keyControl) { InitializeComponent(); this.Size = keyControl.Size; this.HandleCreated += FrmDownBoard_HandleCreated; this.HandleDestroyed += FrmDownBoard_HandleDestroyed; this.Controls.Add(keyControl); keyControl.Dock = DockStyle.Fill; Point p = parentControlc.Parent.PointToScreen(parentControlc.Location); int intX = 0; int intY = 0; if (p.Y + parentControlc.Height + keyControl.Height > Screen.PrimaryScreen.Bounds.Height) { intY = p.Y - keyControl.Height-1; } else { intY = p.Y + parentControlc.Height+1; } if (p.X + keyControl.Width > Screen.PrimaryScreen.Bounds.Width) { intX = Screen.PrimaryScreen.Bounds.Width - keyControl.Width; } else { intX = p.X; } this.Location = new Point(intX, intY); } public FrmAnchor(Size size,Point location, Control keyControl) { InitializeComponent(); this.Size = keyControl.Size; this.HandleCreated += FrmDownBoard_HandleCreated; this.HandleDestroyed += FrmDownBoard_HandleDestroyed; this.Controls.Add(keyControl); keyControl.Dock = DockStyle.Fill; Point p = location; int intX = 0; int intY = 0; if (p.Y + size.Height + size.Height > Screen.PrimaryScreen.Bounds.Height) { intY = p.Y - keyControl.Height - 1; } else { intY = p.Y + size.Height + 1; } if (p.X + keyControl.Width > Screen.PrimaryScreen.Bounds.Width) { intX = Screen.PrimaryScreen.Bounds.Width - keyControl.Width; } else { intX = p.X; } this.Location = new Point(intX, intY); } private void FrmDownBoard_HandleDestroyed(object sender, EventArgs e) { Application.RemoveMessageFilter(this); } private void FrmDownBoard_HandleCreated(object sender, EventArgs e) { Application.AddMessageFilter(this); } #region 无焦点窗体 [System.Runtime.InteropServices.DllImport("user32.dll")] private extern static IntPtr SetActiveWindow(IntPtr handle); private const int WM_ACTIVATE = 0x006; private const int WM_ACTIVATEAPP = 0x01C; private const int WM_NCACTIVATE = 0x086; private const int WA_INACTIVE = 0; private const int WM_MOUSEACTIVATE = 0x21; private const int MA_NOACTIVATE = 3; protected override void WndProc(ref Message m) { if (m.Msg == WM_MOUSEACTIVATE) { m.Result = new IntPtr(MA_NOACTIVATE); return; } else if (m.Msg == WM_NCACTIVATE) { if (((int)m.WParam & 0xFFFF) != WA_INACTIVE) { if (m.LParam != IntPtr.Zero) { SetActiveWindow(m.LParam); } else { SetActiveWindow(IntPtr.Zero); } } } base.WndProc(ref m); } #endregion public bool PreFilterMessage(ref Message m) { if (m.Msg != 0x0201 || this.Visible == false) return false; var pt = this.PointToClient(MousePosition); this.Visible = this.ClientRectangle.Contains(pt); return false; } }
效果如下:
作者:冰封一夏
出处:http://www.cnblogs.com/bfyx/
HZHControls官网:http://www.hzhcontrols.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,
且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
GitHub:https://github.com/kwwwvagaa/NetWinformControl
码云:https://gitee.com/kwwwvagaa/net_winform_custom_control.git