如何创建悬停的 C# Winforms 控件 [英] How to create a C# Winforms Control that hovers

查看:28
本文介绍了如何创建悬停的 C# Winforms 控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建超出其区域边界的 C# Winforms 控件?比如下拉框.有点像你在小面板中有一个 DropDownBox.

How can you create a C# Winforms control which goes out of the bounds of its region? Such as a drop down box. Kind of like if you had a DropDownBox in a Small Sized Panel.

推荐答案

Windows Forms 不能很好地支持 Windows,它与设计器从根本上不兼容.这里有一些代码可以帮助您入门.您不能在设计器中使用此控件,它必须在运行时创建.您还必须自己调用它的 Dispose() 方法.

Windows Forms doesn't support windows like that well, it is pretty fundamentally incompatible with the designer. Here's some code to get you started. You can't use this control in the designer, it must be created at run-time. You also must call its Dispose() method yourself.

using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;

public class MyListBox : ListBox {
  private Control mParent;
  private Point mPos;
  private bool mInitialized;

  public MyListBox(Control parent) {
    mParent = parent;
    mInitialized = true;
    this.SetTopLevel(true);
    parent.LocationChanged += new EventHandler(parent_LocationChanged);
    mPos = mParent.Location;
  }

  public new Point Location {
    get { return mParent.PointToClient(this.Location); }
    set { 
      Point zero = mParent.PointToScreen(Point.Empty);
      base.Location = new Point(zero.X + value.X, zero.Y + value.Y);
    }
  }

  protected override Size DefaultSize {
    get {
      return mInitialized ? base.DefaultSize : Size.Empty;
    }
  }

  protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
    if (this.mInitialized)
      base.SetBoundsCore(x, y, width, height, specified);
  }

  void parent_LocationChanged(object sender, EventArgs e) {
    base.Location = new Point(base.Left + mParent.Left - mPos.X, base.Top + mParent.Top - mPos.Y);
    mPos = mParent.Location;
  }

  protected override CreateParams CreateParams {
    get {
      CreateParams cp = base.CreateParams;
      if (mParent != null && !DesignMode) {
        cp.Style = (int)(((long)cp.Style & 0xffff) | 0x90200000);
        cp.Parent = mParent.Handle;
        Point pos = mParent.PointToScreen(Point.Empty);
        cp.X = pos.X;
        cp.Y = pos.Y;
        cp.Width = base.DefaultSize.Width;
        cp.Height = base.DefaultSize.Height;
      }
      return cp;
    }
  }
}

这篇关于如何创建悬停的 C# Winforms 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆