C#调用dll!!!!!!!!!!!!!
想做一个训练软件,实现的功能是给游戏提供一个接口,训练软件就可以外加载游戏并且可以控制游戏,现在想把游戏做成dll文件(如dodger.dll),公共接口Myinterface也做成dll文件(Myinterface.dll),那应该怎么在程序中通过接口将游戏加载进去呢?并显示游戏窗口??
先来说明一下解决方案,
由于不知道怎么发图,说明起来有点困难,加上本人没什么文化,你将就着看,有错漏或看不懂的请多包涵!整个解决方案包含三个项目:
1、DllCallDllForm,这是所谓的训练器,他引用Tranning.Controller,FormMain是训练器的窗口;
2、Tranning.Controller是一个类库项目,是所谓的接口,他引用Game,记得要添加System.Windows.Forms的引用;
3、Game,这是所谓的游戏,在这个项目里添加一个Interface.cs文件并在其中添加MyInterface接口,FormGame是游戏的窗体,它继承MyInterface接口,如果你是希望以后有N个游戏都可以用Controller通用控制的话,新建一个类库项目,把MyInterface的定义单独放到里面,每个游戏都引用,并且Controller也引用这个库就可以了。在项目属性里面把输出类型设置为类库。
FormMain包含三个Button“打开游戏”、“关闭游戏”和“向游戏发送消息”和一个TextBox用于输入要发送到游戏的信息;
FormGame包含一个TextBox,从训练器发过来的信息将显示在里面。
运行后,FormMain实例化一个Controller,通过调用Controller的OpenGame方法可以打开一个游戏窗口,调用CloseGame方法可以关闭游戏,ShowMessage方法可向FormGame发送信息;而Controller则调用接口的Close和ShowInfo方法来关闭游戏窗口和显示消息。在接口中定义更多的方法就可在Game中轻易扩展你的规则了。
到此,按照我的理解你想要的应该是这个样子的吧。
各部分代码如下:
程序代码://Interface.cs
namespace Game
{
public interface MyInterface
{
void Close();
void DoXX();
void ShowInfo(string info);
}
}
//FormGame.cs
using System.Windows.Forms;
namespace Game
{
public partial class FormGame : Form, MyInterface
{
#region 构造函数
public FormGame()
{
InitializeComponent();
}
#endregion
#region 接口实现
public void DoXX()
{
}
public void ShowInfo(string info)
{
TbInfo.AppendText(string.Concat(info, "\r\n"));
}
#endregion
}
}
//Controller.cs
using Game;
namespace Tranning.Controller
{
public class Controller
{
#region 全局字段
private MyInterface _myInterface;
#endregion
#region 公共方法
public void CloseGame()
{
_myInterface.Close();
}
public void OpenGame()
{
var formGame = new FormGame();
formGame.Show();
_myInterface = formGame;
}
public void ShowMessage(string s)
{
_myInterface.ShowInfo(s);
}
#endregion
}
}
//FormMain.cs
using System;
using System.Windows.Forms;
using Tranning.Controller;
namespace DllCallDllForm
{
public partial class FormMain : Form
{
#region 只读全局字段
private readonly Controller _controller;
#endregion
#region 构造函数
public FormMain()
{
InitializeComponent();
_controller = new Controller();
}
#endregion
#region 构造函数
private void ButCloseGame_Click(object sender, EventArgs e)
{
_controller.CloseGame();
}
private void ButOpenGame_Click(object sender, EventArgs e)
{
_controller.OpenGame();
}
private void ButSendInfo_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(TbMessage.Text)) return;
_controller.ShowMessage(TbMessage.Text);
}
#endregion
}
}
[ 本帖最后由 mmxo 于 2012-11-7 21:30 编辑 ]








