简体   繁体   English

如何在类库C#中使用Messagebox?

[英]How to use Messagebox in class library c#?

How to use MessageBox in class library? 如何在类库中使用MessageBox?

Here is my code 这是我的代码

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

namespace MessageBoxes
{
    class ShowInfo
    {
        MessageBox.Show("test");
    }
}

i can load MessageBox but can't have show property, MessageBox.Show("test"); 我可以加载MessageBox但不能具有show属性,MessageBox.Show(“ test”); <-- fail <-失败

You should NOT use a Windows forms MessageBox inside a class library . 应该使用一个Windows窗体MessageBox的 类库里面。 What if you use this library in an ASP.NET application. 如果在ASP.NET应用程序中使用此库,该怎么办。 The MessageBox will be shown in Webserver. MessageBox将显示在Web服务器中。 And your webserver will be waiting (hung) untill someone responds to that MessageBox in webserver. 并且您的Web服务器将一直等待(挂起),直到有人响应Web服务器中的该MessageBox。

An ideal design would be that you either return the message as string and deal with that string in caller specific way or throw an exception if thats what you want. 理想的设计是,您要么以字符串形式返回消息,然后以调用者特定的方式处理该字符串,要么就这样抛出异常。

If you still want then here is your code corrected 如果您仍然想要,那么这里的代码已更正

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

namespace MessageBoxes
{
    class ShowInfo
    {
        public void ShowMessage(string msg)
        {
            MessageBox.Show(msg);
        }
    }
}

You have the call to messagebox outside any method. 您可以通过任何方法来调用消息框。
This code cannot be compiled at all. 此代码完全不能编译。

You should write 你应该写

namespace MessageBoxes
{
    class ShowInfo
    {
        public void ShowUserMessage(string messageText)
        {
             MessageBox.Show(messageText);
        }
    }
}

and then call it after instancing an object of type ShowInfo 然后实例化ShowInfo类型的对象后调用它

ShowInfo info = new ShowInfo();
info.ShowUserMessage("This is a Test");

Additional Answer to this Question: 此问题的其他答案:

After the Class Library Project has been created. 创建类库项目之后。

Right Click your Project Add > New Item > Windows form 右键单击您的项目,然后单击Add > New Item > Windows form

it's done by adding reference System.Windows.Forms.dll 通过添加参考System.Windows.Forms.dll

Make sure you actually use the the class in the main form. 确保您在主窗体中实际使用了该类。

class ShowInfo
{
    public static void show()
    {
        System.Windows.Forms.MessageBox.Show("test");
    }
}

... ...

    public Form1()
    {
        InitializeComponent();
        ShowInfo.show();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM