用C#从控制台调用Windows表单

3
我正在使用C#.net 4.0 VS 2010。
我在Stackoverflow上复制了以下代码,并确认所有内容都是可以工作的。但是在我的调用“Application.Run(new ShoutBox());”时,我遇到了语法错误,错误为“The type or namespace 'ShoutBox' could not be found.”。
该项目最初构建为控制台应用程序。我最近添加了一个名为ShoutBox的窗体,并将其保存为ShoutBox.cs。我已将代码转移到表单中,因此它不会在控制台上显示,而是在我创建的窗体的文本框中显示。
我错过了什么?我该如何使其工作?
    using System;
    using System.Windows.Forms;

    namespace ChatApp
    {
        class ConsoleApplication1
        {


            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();


                //this one works
                Application.Run(new Form()); // or whatever


                //this one does not work, error on second ShoutBox
                Form ShoutBox = new Form();
                Application.Run(new ShoutBox()); 
            }


        }
    }

仅供参考,以下是我的最终工作代码: 此代码创建一个新的 Shoutbox 表单,而不是一个空白表单。

    using System;
    using System.Windows.Forms;
    using ShoutBox; // Adding this

    namespace ChatApp
    {
        class ConsoleApplication1
        {        
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Form ShoutBox1 = new ShoutBox.ShoutBox(); //Changing this
                Application.Run(ShoutBox1);               //Changing this
            }
        }
    }

我的Shoutbox表单如下:
    using System
    using System.Windows.Forms;
    namespace ShoutBox
    {
        public partial class ShoutBox : Form
        {
    ....

这只是一个简单的编译错误。搜索“找不到类型或命名空间。”您可能缺少引用(ShoutBox类是否在不同的项目中?)和/或缺少使用(ShoutBox类是否在不同的命名空间中?)和/或不存在(ShoutBox类是否在任何地方定义?) - 有许多答案涵盖了这一点,它与表单没有任何内在关系。简而言之:所涉及的代码无法解析ShoutBox类型 - user2246674
3个回答

5
`ShoutBox`是一个变量名称,引用了一个表单。你不能调用`new ShoutBox()`。
在前一行中,你已经实例化了表单,现在只需要简单地调用它即可。
 Application.Run(ShoutBox); 

但是,如果您有一个名为ShoutBox的表单,定义如下:

namespace ShoutBox
{
     public partial class ShoutBox: Form
     {
        .....
     }
}

那么您需要在文件开头添加使用声明。
using ShoutBox;

或者你可以直接在 ShoutBox.cs 文件中更改命名空间为程序主文件使用的相同命名空间。

namespace ChatApp
{
     public partial class ShoutBox: Form
     {
        ....    
     }
}

这解决了问题。谢谢。我会尽快接受的。 - Ace Caserya

0

你可能缺少了一两个东西。

首先,你需要导入包含 ShoutBox 的命名空间:

using Your.Namespace.Where.ShoutBox.Is.Declared;

在Visual Studio中实现这个功能的简单方法是将光标放在单词ShoutBox上,然后按下Alt+Shift+F10或者像一些比我更高效的人那样,按下Ctrl+.。这将会弹出一个菜单,显示需要包含的命名空间。

另外,如果该命名空间位于另一个程序集中(你提到了这一点),则需要将其添加为项目的引用。

还有这个:

Form ShoutBox = new Form();
Application.Run(new ShoutBox());

..是不正确的。我建议学习基本类的创建教程。


0

ShoutBox类可能在不同的命名空间中。

而且代码Form ShoutBox = new Form();是无用的,你只需要Application.Run(new ShoutBox());


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接