日期:2014-05-18  浏览次数:20725 次

C#窗体关闭
请问大神们,这样之后怎么关闭窗体。。小弟刚搞这个,不是很会。求解ing。。

C# code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Dynamic
{
    public partial class Dynamic : Form
    {
        public Dynamic()
        {
            InitializeComponent();
        }

        int offset = 25;//垂直增量
        int offset1 = 25;//水平增量

        private void Dynamic_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer_dynamic.Enabled = true;
            e.Cancel = true;
        }  

        private void timer_dynamic_Tick(object sender, EventArgs e)
        {
            this.Top += offset;
            this.Height -= 70;
            if (this.Top > 300)
            {
                offset = 0;
                this.Left += offset1;
                this.Width = -50;
                if (this.Left > 600)
                {
                    offset1 = 0;

                }
            }
        }
    }
}



------解决方案--------------------
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (MessageBox.Show(this, "确定退出系统?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
this.Dispose();
GC.Collect();
Application.Exit();
}
else
{
e.Cancel = true;
}
}
------解决方案--------------------
探讨

引用:

e.Cancel = true;去掉


e.Cancel = true;
是我为了捕获关闭事件。你可以测试下我的代码,我是想在实现那种效果之后在关闭。。

------解决方案--------------------
不知道你要执行动作之后自动关闭还是手动关闭?(应该是自动关闭吧)
(1)如果自动关闭,那么添加两个临时变量,用于检测何时关闭窗体。并在FormClosing事件中,将e.Cancel=true;改为根据timer的Enabled来调整。具体代码如下(具体变量名与你的不一样,自己改动):
C# code
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int offset = 25;//垂直增量
        int offset1 = 25;//水平增量

        int tempHeight;
        int tempWidth;

        private void timer1_Tick(object sender, EventArgs e)
        {
            tempHeight=this.Height;
            tempWidth=this.Width;
            this.Top += offset;
            this.Height -= 70;
            if (this.Top > 300)
            {
                offset = 0;
                this.Left += offset1;
                this.Width -=50;
                if (this.Left > 600)
                {
                    offset1 = 0;

                }
            }
            if(this.Width==tempWidth&&this.Height==tempHeight)
            {
                this.Close();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer1.Enabled = !timer1.Enabled;
            if (timer1.Enabled)
            {
                e.Cancel = true;
            }
        }
    }

------解决方案--------------------
你在关闭事件中调用你写的要显示效果的方法不就行了嘛
 private void Dynamic_FormClosing(object sender, FormClosingEventArgs e)
{
timer_dynamic.Enabled = true;
timer_dynamic_Tick(null, null);
}