在运行时调用表单 [英] call form at runtime

查看:56
本文介绍了在运行时调用表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好
我有几种名为form1,form2等的表格.
我需要动态调用

我的代码生成错误:
找不到类型或名称空间名称"Form1"(您是否缺少using指令或程序集引用?)

hi all
I have several forms named form1, form2, etc..
I need to dynamically invoke

I code generates the error:
Can not find the type or namespace name ''Form1'' (are you missing a using directive or an assembly reference?)

string MyForm = FormName; // form1, form2 ,etc.
CodeDomProvider objc = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters CompilerParameters objCParams = new();
objCParams.CompilerOptions = "/target:library /optimize";
objCParams.GenerateExecutable = false;
objCParams.GenerateInMemory = true;
objCParams.IncludeDebugInformation = false;
objCParams.ReferencedAssemblies.Add("mscorlib.dll");
objCParams.ReferencedAssemblies.Add("System.dll");
objCParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");

CompilerResults objComResults = 
    objC.CompileAssemblyFromSource(objCParams,ToCompile(MyForm));
if (objComResults.Errors.Count == 0)
{
    Module[] mods = objComResults.CompiledAssembly.GetModules(false);
    foreach (Type type in mods[0].GetTypes())
    {
        MethodInfo mi = type.GetMethod("RunForm", BindingFlags.Public |
             BindingFlags.Static);
        if ((my! = null))
            mi.Invoke(null, null); // Invoke the method
    }
}
public string ToCompile(string pFrm)
{
    StrCode StringBuilder = new StringBuilder (1000);
    strCode.AppendLine ("using System;");
    strCode.AppendLine ("using System.Windows.Forms;");
    strCode.AppendLine ("namespace DynamicCC");
    strCode.AppendLine ("{");
    strCode.AppendLine ("    Dynamic public class");
    strCode.AppendLine ("    {");
    strCode.AppendLine ("        public static void RunForm ()");
    strCode.AppendLine ("        {");
    strCode.AppendLine ("            Form frm = new" + pFrm + "()");
    strCode.AppendLine ("            frm.Show ();");
    strCode.AppendLine ("        }");
    strCode.AppendLine ("    }");
    strCode.AppendLine ("}");

    return strCode.ToString();
}


如果我使用


if i use

strCode.AppendLine("Form frm = new Form ();");


没问题

感谢


no problem

thanks

推荐答案

我已将您的代码粘贴到WinForms .NET 4.5 C#项目中,并对其进行了检查并尝试进行构建.

您的代码(如此处所示)具有多个语法/键入错误,这些错误会阻止其构建,更不用说运行了.然而,您暗示,在这里,您确实有一个可行的例子;这让我感到困惑.

因此,解决此问题的第1步是:采用当前解决方案并进行构建:如果构建中没有错误:这意味着您在此处发布的代码不是正在使用:在这种情况下:将您在此处显示的代码更新为要构建的代码 .

注意:最好包含使用此处所需的语句以使此代码起作用,以及NameSpace和Class定义.

请参阅此响应末尾的进一步注释[1],以获取有关此处未显示给我们的可能很重要的代码的进一步注释.

但是,让我们来帮助您弄清楚如何使此代码正常工作(假设您有一个可以构建的版本):

在"ToCompile"方法的末尾,一个停止显示"并查看发生了什么的好地方:
I have taken your code, pasted it into a WinForms .NET 4.5 C# project, and examined it, and tried to build it.

Your code, shown here, has several syntax/typing errors that would stop it from ever building, let alone running. Yet, you imply, here, that you do have a working example; that puzzles me.

So step #1 towards fixing this is: take your current solution, and build it: if there are no errors in the build: it means the code you have posted here is not the code you are using: in that case: update the code you show here to the same code that does build.

Note: it would be best for you to include the ''Using statements required here for this code to work, and the NameSpace and Class definition.

See further comments [1] at the end of this response for further comments on, possibly quite important code, that you did not show us, here.

But, let''s get to helping you figure out how to get this code working (assuming you have a version that does build):

A good place to "stop the show," and see what''s going on is right at the end of the ''ToCompile method:
// take a look at the code you actually output
Console.WriteLine(strCode.ToString());

// put a breakpoint on this line
return strCode.ToString();

在运行代码时,遇到该断点,然后在Visual Studio中打开输出"窗口,然后检查代码(字符串)将要执行.

该代码中的一个非常基本的语法错误应向您跳出"!而且,当您查看该代码并进行更仔细的研究时,希望您会考虑执行该代码可能会丢失的其他重要事项[1].

因此,对策略作最后的评论:我认为拥有清晰的工作模型"以明确需要以这种动态"方式生成什么代码非常有价值:

我建议创建一个原型,一个类似这样的类:

When you run your code, and hit that breakpoint, then open an Output window in Visual Studio, and examine the code (the string) that you will be executing.

A very basic syntax error in that code should "jump" out at you ! And, as you look at that code, and study it more carefully, hopefully you will think about other important things that code may be missing in order to execute [1].

So, a final comment on strategy: I think it''s very valuable to have a clear "working model" of exactly what code you need to generate in this "dynamic" way:

I suggest creating a prototype, a class something like this:

using System;
// make sure you have all necessary
// 'Using statements

namespace UnKnownNameSpace
{
    public class TestClass
    {
        public static void RunForm()
        {
            // I leave this to you to fix/change/implement
        }
    }
}

然后,下一步是测试该类的外部"静态方法"RunForm"的调用方式,并考虑到该原型测试台的NameSpace与该原型的NameSpace之间的任何差异.从中调用该静态方法的类.

这是我从另一个NameSpace中的另一个类测试它的方式:

And then, the next step is to test how you would call that static method ''RunForm from "outside" this class, taking into account any difference between the NameSpace of this prototype test-bed, and the NameSpace of the class from which you invoke that static method.

Here''s how I tested it from another class in another NameSpace:

UnknownNameSpace.TestClass.RunForm();

祝您好运,Bill

[1]显然,您没有在此处包括方法名称和签名,该名称和签名将封装示例中的所有代码,直至下一行:

公共字符串ToCompile(string pFrm)"

更重要的是,您不会向我们显示代码在其中运行所需的引用(使用语句")或NameSpace名称.

我们不知道此代码是否存在于其自己的唯一NameSpace中的单独类中,或者它是否是与其他类共享NameSpace的类.

或者,如果此代码是嵌入式代码:嵌入到其他一些Class中.

我们可以确定您使用的是非静态的封装类,因为:"ToCompile"的方法签名不是静态的,因此很明显,您将创建某个类的新实例以使用它:

恕我直言:您肯定应该将此代码放在单独的类中,并且没有理由Class不能是静态的.

当然,如果您将Class设为静态,则需要...在此处填写答案...:)

good luck, Bill

[1] Obviously, you did not include here the method name, and signature, that would encapsulate all the code in your example down to the line beginning:

"public string ToCompile(string pFrm)"

More importantly you don''t show us the required references (the ''Using statements), or the NameSpace name, in which your code runs.

We don''t know if this code exists in a separate Class in its own unique NameSpace, or if it''s a Class that shares a NameSpace with other Classes.

Or, if this code is in-line: embedded in some other Class.

We can be sure you are using an encapsulating Class that is not static because: the method signature of ''ToCompile is not static, so obviously you''ll be creating a new instance of some Class to use it:

imho: you definitely should have this code in a separate class, and there''s no reason that Class cannot be static.

Of course, if you make the Class static, you''ll need to ... you fill in the answer here ... :)


我在codeproject上发现了这一点:

字符串myFormName ="Form1"; //Form2,Form3等
Assembly myAssembly = Assembly.GetExecutingAssembly();
表格frm =(Form)myAssembly.CreateInstance("MyNameSpace." + myFormName);
frm.Show();
I found this on codeproject:

string myFormName = "Form1"; // Form2, Form3, etc.
Assembly myAssembly = Assembly.GetExecutingAssembly();
Form frm = (Form)myAssembly.CreateInstance("MyNameSpace." + myFormName);
frm.Show();


没有这样的概念,例如呼叫表格".一个人可以调用一个方法/函数/过程/子例程,一个运算符,甚至是一个属性(因为它可能有一个setter或一个getter).

没有在运行时对表单进行任何处理的事情.

这个问题没有任何意义,没有对问题进行解释,但是我正式回答了.很抱歉,它不能解决任何特定问题,但是它应该可以帮助您对编程有所了解,并以明智的方式提出下一个问题. br/>
—SA
There is no such concept as "call a form", period. One can call a method/function/procedure/subroutine, an operator, even a property (because it may have a setter a getter or both).

There is no such thing as doing anything with the form not at run time.

The question makes no sense, and the problem is not explained, but formally I answered, sorry that it does not solve any particular problem, but it should help you to get some understanding of programming and ask your next question in a sensible way.

—SA


这篇关于在运行时调用表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆