0

我想在我的 Windows 窗体应用程序中创建一个控件。该控件包含一些数据作为datagridview 控件。但我的要求是将此控件显示为弹出控件。下面是这个的屏幕截图。

在此处输入图像描述

请帮助我克服这个问题。任何帮助表示赞赏。

注意:- 我希望我的表单与上面的屏幕截图相同,这意味着我只希望我的 datagridview 可见,我不希望表单标题及其边框。

4

1 回答 1

1

您可以使用以下代码创建自己的 PopupForm。

要删除边框,请使用FormBorderStyle

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

然后像这样放置你的 DataGridView 和你的按钮: 示例弹出窗口

使用 DataGridView 的 Dock-Property 填充表单:

yourDataGridViewControl.Dock = DockStyle.Fill;

将您的按钮放在右上角并创建一个EventHandler来捕获Click-Event

button_close.Click += button_close_Click;
private void button_close_Click(object sender, EventArgs e)
{
    this.Close();
}

在您的 Mainform 中: 创建以下两个字段:

PopupForm popup; //PopupForm is the name of your Form
Point lastPos; //Needed to move popup with mainform

使用以下代码在按钮的位置显示您的弹出窗口:

void button_Click(object sender, EventArgs e)
{
    if(popup != null)
        popup.Close(); //Closes the last open popup

    popup = new PopupForm();
    Point location = button.PointToScreen(Point.Empty); //Catches the position of the button
    location.X -= (popup.Width - button.Width); //Set the popups X-Coordinate left of the button
    location.Y += button.Height; //Sets the location beneath the button
    popup.Show();
    popup.TopMost = true; //Is always on top of all windows
    popup.Location = location; //Sets the location

    if (popup.Location.X < 0) //To avoid that the popup 
        popup.Location = new Point(0, location.Y); //is out of sight
}

创建一个 EventHandler 来捕捉 MainForm 的 Move-Event 并使用以下方法使用 MainForm 移动弹出窗口(感谢 Hans Passant):

private void Form1_LocationChanged(object sender, EventArgs e)
{
    try
    {
        popup.Location = new Point(popup.Location.X + this.Left - lastPos.X,
            popup.Location.Y + this.Top - lastPos.Y);
        if (popup.Location.X < 0)
            popup.Location = new Point(0, popup.Location.Y);
    }
    catch (NullReferenceException)
    {
    }
    lastPos = this.Location;
}

在这里你可以得到演示项目:LINK

于 2013-11-01T10:43:45.207 回答