我正试图从C++中使用CLI Wrapper调用C#类。我想我几乎在那里,但我的表格不能正确显示。虽然我怀疑这可能与它有自己的线程有关,但我不完全确定我在做什么,因此我在做什么错误。希望你们能为我提供一些启示。C#.NET窗体在C++/CLI中不能正确显示
这里的形式(很无趣):http://i.imgur.com/U2XisT3.png
TestForm.cs
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 ManagedForms
{
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
}
private void TestForm_Load(object sender, EventArgs e)
{
}
public void changeLabel()
{
this.label1.Text = "Now I have new text!!";
}
}
}
ManagedFormsCLIWrapper.h
class TestFormWrapperPrivate;
class TestFormWrapper
{
private:
TestFormWrapperPrivate* _private;
public:
TestFormWrapper();
~TestFormWrapper();
void ShowForm();
void ChangeLabel();
};
ManagedFormsCLIWrapper.cpp
#using "..\ManagedForms\bin\Debug\ManagedForms.dll"
#using <System.Windows.Forms.dll>
#using <System.dll>
#include <msclr\auto_gcroot.h>
using namespace System::Runtime::InteropServices;
class TestFormWrapperPrivate
{
public: msclr::auto_gcroot<ManagedForms::TestForm^> testForm;
};
class __declspec(dllexport) TestFormWrapper
{
private:
TestFormWrapperPrivate* _private;
public:
TestFormWrapper()
{
_private = new TestFormWrapperPrivate();
_private->testForm = gcnew ManagedForms::TestForm();
}
~TestFormWrapper()
{
delete _private;
}
void ShowForm()
{
_private->testForm->Show();
}
void ChangeLabel()
{
_private->testForm->changeLabel();
}
};
的main.cpp
#include "ManagedFormsCLIWrapper.h"
#include <iostream>
int main()
{
int fred;
TestFormWrapper testForm;
testForm.ShowForm();
std::cin >> fred; // to allow me to see the form before and after label change
testForm.ChangeLabel();
std::cin >> fred; // to allow me to see the form before and after label change
return 0;
}
三个项目中存在在我的解决方案中的文件:
http://i.imgur.com/fjxevg2.png
和执行并成功启动形式,但有什么地方了:标签丢失。
http://i.imgur.com/4locuB0.png
输入的东西到控制台进步到标签还挺改写作品:白色区域已更改大小:
http://i.imgur.com/urG7P0z.png
但是,内容不显示,和鼠标悬停将指针更改为每个人最喜欢的“思考”指针。
有什么想法?
任何窗口总是需要一个消息循环。你永远不会调用'Application.Run'来运行消息循环,所以你的窗口永远不会自己绘制。它会直接从C#执行同样的操作# – 2014-10-02 12:23:16
@Dark是否意味着我只能使用这种技术从我的托管库中访问非UI类,还是有办法让表单工作呢? – technorabble 2014-10-02 12:34:53
是的,它可以工作。您需要在窗体上调用'Show'的同一个线程的某个地方调用'Application.Run'。 – 2014-10-02 12:44:26