C#表单应用程序在页面之间移动

时间:2014-07-16 11:07:27

标签: c#

我正在建造一个游戏。我有一个菜单页面,带有“开始”按钮。我想知道如何让按钮将用户引导到游戏的新页面。我想过简单地将所有按钮和标签的可见性改为假,但这会非常混乱。我想要关闭表格并重新打开一个新的,如下所述:

http://social.msdn.microsoft.com/Forums/windows/en-US/936c8ca3-0809-4ddb-890c-426521fe60f1/c-open-a-new-form-and-close-a-form?forum=winforms

像这样:

public static void ThreadProc()
        {
            Application.Run(new Form());
        }

    private void button1_Click(object sender, EventArgs e)
    {
        System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
        t.Start();
        this.Close();
    }

但是当我点击按钮时,您可以看到表单关闭并再次重新打开,它甚至不会在相同的坐标处重新打开。 有没有办法做这样的事情?如果这是一个网站,我希望它从一个页面移动到另一个页面。这可能吗?如果是这样的话?在此先感谢: - )

1 个答案:

答案 0 :(得分:0)

UserControl用于您需要的每个视图,然后在代码中通过向/从表单添加/删除它们来切换它们。

示例:起始页面是UserControl,其中包含启动游戏的按钮。游戏UI是另一个UserControl,其中包含游戏的所有逻辑和视觉效果。

然后你可以使用像他这样的东西:

public class StartView : UserControl
{
    ...

    private void btnStart_Click(object sender, EventArgs e)
    {
        // Raise a separate event upon the button being clicked
        if (StartButtonPressed != null)
            StartButtonPressed(this, EventArgs.Empty);
    }

    public event EventHandler<EventArgs> StartButtonPressed;
}

public class GameView : UserControl
{
    ...
}

public UserControl SwitchView(UserControl newView)
{
    UserControl oldControl = null;
    if (this.Controls.Count > 0)
    {   oldControl = (UserControl)this.Controls[0];
        this.Controls.RemoveAt(0);
    }

    this.Controls.Add(newView);
    newView.Dock = DockStyle.Fill;

    return oldControl;
}

您现在可以在Form_Load中创建开始视图:

public void Form_Load(object sender, EventArgs e)
{
    StartView v = new StartView();
    v.StartButtonPressed += StartButtonPressed;
    SwitchView(v);
}

对按下的开始按钮作出反应的事件处理程序将执行此操作:

public void StartButtonPressed(object senderView, EventArgs e)
{
    GameView v = new GameView();
    UserControl old = SwitchView(v);
    if (old != null)
        old.Dispose();
}
相关问题