C#.NET窗体在C++/CLI中未正确显示

本文关键字:显示 CLI NET 窗体 C++ | 更新日期: 2023-09-27 18:25:29

我正在尝试使用CLI包装器从C++调用C#类。我想我差不多到了,但我的表格显示不正确。尽管我怀疑这可能与它有自己的线索有关,但我并不完全确定我在做什么,因此我也不确定我做错了什么。希望你们能为我提供一些线索。

这是表格(很没意思):https://i.stack.imgur.com/qWg51.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;
}

这些文件存在于我的解决方案中的三个项目中:

https://i.stack.imgur.com/rERQW.png

执行确实成功地启动了表单,但出现了一些问题:缺少标签。

https://i.stack.imgur.com/8MPDj.png

在控制台中输入一些内容以进行标签重写有点奏效:白色区域的大小发生了变化:

https://i.stack.imgur.com/9Os2w.png

但是,内容不会显示,mouseover会将指针更改为每个人最喜欢的"思考"指针。

有什么想法吗?

C#.NET窗体在C++/CLI中未正确显示

这似乎有效:

void ShowForm()
{
    _private->testForm->Show();
    _private->testForm->Refresh();
}
void ChangeLabel()
{
    _private->testForm->changeLabel();
    _private->testForm->Refresh();
}