如何在winforms中将一个表单放在另一个表单上方?

时间:2014-04-22 10:09:36

标签: c# winforms notifications new-window

我正在创建一个winforms应用程序,我将不时收到一些消息或事件的通知。 我期待的通知风格就像Gtalk那样,如果用户发送消息,它会在屏幕右下角显示通知,如果有来自另一个用户的消息同时出现新消息通知窗口将显示在上一个窗口的正上方。新窗口不会与旧窗口重叠或遮挡。

到目前为止,我已经取得了一些成就

在构造函数中使用此代码获取窗口右下角的窗口并不是一件大事

    Rectangle workingArea = Screen.GetWorkingArea(this);
    this.Location = new Point(workingArea.Right - Size.Width, workingArea.Bottom - Size.Height);

但现在一旦名为" Notify"在屏幕右下角打开。当新通知出现时,它只是重叠前一个表单。有什么我可以做的吗?我错过了一些非常明显的东西吗?

1 个答案:

答案 0 :(得分:1)

这是带有按钮的父表单,可以创建新的通知表单:

public partial class Parent_Form : Form
{
    public static List<Form> activeNotifications = new List<Form>();

    public Parent_Form()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Notification notification = new Notification();
        activeNotifications.Add(notification);
        notification.Show();
    }

    public static void SortNotifications()
    {
        int additionalHeight = 0;
        foreach (Form notification in activeNotifications)
        {
            notification.Location = new Point(0, (0 + additionalHeight));
            additionalHeight += notification.Height;
        }
    }

    public static Point GetLocation()
    {
        int height = 0;
        foreach (Form notification in Parent_Form.activeNotifications) { height += notification.Height; }
        return new Point(0, height);
    }
}

父表单包含一个button1,用于创建新通知

这是通知表单示例:

public partial class Notification : Form
{
    public Notification()
    {
        InitializeComponent();
        this.Location = Parent_Form.GetLocation();
        this.FormClosing += Notification_FormClosing;
    }

    private void button1_Click(object sender, EventArgs e) { this.Close(); }

    private void Notification_FormClosing(object sender, FormClosingEventArgs e)
    {
        Parent_Form.activeNotifications.Remove(this);
        Parent_Form.SortNotifications();
    }
}

通知仅包含button1,用于关闭通知表单。确保通知表单使用StartPosition&#34; Manual&#34;。