本文转自:http://www.cnblogs.com/jiangshaofen/archive/2008/07/13/1242036.html
在一般应用程序中,经常有个主登陆窗体,做验证及其他等操作。为保持公司项目(或是产品)的一致性,常将其固化,在项目开发时候直接引用之即可。下面做个简单的事例程序。具体创建工程,添加项目过程略过,下面是创建好以后的解决方案图:
主要步骤:
1: 在类库项目Main中要添加对System.Drawing和System.Windows.Forms的引用;
2:在类库项目Main的属性中改变其输出类型为Windows 应用程序,输出路经为 ..\;
3:在类库项目Test的属性中改变其输出路经为..\;
MainStart.cs基本代码实现如下:
1
using System;
2
using System.Drawing;
3
using System.Collections;
4
using System.ComponentModel;
5
using System.Windows.Forms;
6
using System.Data;
7
using System.Diagnostics;
8
using System.Reflection;
9
using System.Threading;
10
using System.Xml;
11
using System.IO;
12
13
namespace Main
14
{
15
/// <summary>
16
/// MainStart 的摘要说明。
17
/// </summary>
18
public class MainStart
19
{
20
public MainStart()
21
{
22
//
23
// TODO: 在此处添加构造函数逻辑
24
//
25
}
26
27
[STAThread]
28
static void Main(string[] args)
29
{
30
31
Assembly a;
32
Type b;
33
Object obj = null;
34
string dll_path = " ";
35
Type[] mytypes;
36
try
37
{
38
dll_path =Path.GetFullPath(".") + "\\Test.dll";
39
40
a = Assembly.LoadFrom(dll_path);
41
42
try
43
{
44
mytypes = a.GetTypes();
45
}
46
catch
47
{
48
}
49
50
b = a.GetType("Test.MainForm");
51
obj = Activator.CreateInstance(b);
52
Application.Run((Form)obj);
53
}
54
catch (Exception e)
55
{
56
57
Console.WriteLine(e.ToString());
58
if (obj != null)
59
{
60
((Form)obj).Close();
61
}
62
return;
63
}
64
65
}
66
67
}
68
}
using System;2
using System.Drawing;3
using System.Collections;4
using System.ComponentModel;5
using System.Windows.Forms;6
using System.Data;7
using System.Diagnostics;8
using System.Reflection;9
using System.Threading;10
using System.Xml;11
using System.IO;12

13
namespace Main14
{15
/// <summary>16
/// MainStart 的摘要说明。17
/// </summary>18
public class MainStart19
{20
public MainStart()21
{22
//23
// TODO: 在此处添加构造函数逻辑24
//25
}26

27
[STAThread]28
static void Main(string[] args) 29
{30

31
Assembly a;32
Type b;33
Object obj = null;34
string dll_path = " ";35
Type[] mytypes;36
try 37
{38
dll_path =Path.GetFullPath(".") + "\\Test.dll"; 39

40
a = Assembly.LoadFrom(dll_path);41
42
try 43
{44
mytypes = a.GetTypes();45
} 46
catch 47
{48
}49

50
b = a.GetType("Test.MainForm");51
obj = Activator.CreateInstance(b); 52
Application.Run((Form)obj); 53
} 54
catch (Exception e) 55
{56
57
Console.WriteLine(e.ToString());58
if (obj != null) 59
{60
((Form)obj).Close();61
}62
return;63
}64

65
}66

67
}68
}4:将Main做为启动项目。编译运行效果如下:


浙公网安备 33010602011771号