c# winform 悬浮窗的效果
时间: 2023-07-28 17:10:44 浏览: 165
要实现C# Winform悬浮窗效果,可以通过以下步骤:
1. 创建一个新的Winform窗体,将窗体的BorderStyle属性设置为None,BackColor属性设置为透明。
2. 在窗体的Load事件中,使用以下代码将窗体设置为悬浮窗口:
```
SetWindowLong(this.Handle, GWL_EXSTYLE, (int)(GetWindowLong(this.Handle, GWL_EXSTYLE) | WS_EX_TOOLWINDOW | WS_EX_TOPMOST));
```
3. 在窗体的MouseMove事件中,使用以下代码实现窗体的拖动:
```
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
```
4. 在窗体的Paint事件中,使用以下代码实现窗体的透明效果:
```
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(50, Color.White)), this.ClientRectangle);
}
```
注意:以上代码中使用了一些Windows API函数,需要在代码文件中添加以下声明:
```
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
const int WM_NCLBUTTONDOWN = 0xA1;
const int HT_CAPTION = 0x2;
const int GWL_EXSTYLE = -20;
const int WS_EX_TOOLWINDOW = 0x80;
const int WS_EX_TOPMOST = 0x8;
```