winforms 在C++中扩展类(System.Windows.Forms.TextBox)

bfrts1fy  于 2023-05-07  发布在  Windows
关注(0)|答案(2)|浏览(191)

在C#中,我经常喜欢创建一个名为“IntTextBox”的自定义类,它只允许有效整数存在于“Text”属性中。

public class IntTextBox : TextBox
{
    string origin = "0";
    //A string to return to if the user-inputted text is not an integer.
    public IntTextBox()
    {
        Text = "0";
        TextChanged += new EventHandler(IntTextBox_TextChanged);
    }
    private void IntTextBox_TextChanged(object sender, EventArgs e)
    {
        int temp;
        if(int.TryParse(Text,out temp))
        //If the value of "Text" can be converted into an integer.
        {
            origin = Text;
            //"Save" the changes to the "origin" variable.
        }
        else
        {
            Text = origin;
            //Return to the previous text value to remove invalidity.
        }
    }
}

我试图在C++中模仿这一点,没有明显的错误,但是当我试图将其添加到我的表单中时,Visual Studio说“未能加载项目'IntTextBox'。它将从工具箱中删除。这是我迄今为止尝试过的代码。

public ref class IntTextBox : public System::Windows::Forms::TextBox
{
    public:
        IntTextBox()
        {
            Text = "0";
            TextChanged += gcnew System::EventHandler(this, &AIMLProjectCreator::IntTextBox::IntTextBox_TextChanged);
        }
    private:
        String^ origin = "0";
        System::Void IntTextBox_TextChanged(System::Object^ sender, System::EventArgs^ e)
        {
            int temp;
            if (int::TryParse(Text, temp))
            {
                origin = Text;
            }
            else
            {
                Text = origin;
            }
        }
};
l7mqbcuq

l7mqbcuq1#

您的C++/CLI项目很可能被设置为生成混合模式的程序集,该程序集部分是CPU独立的CIL(MSIL),部分是本机代码。本机代码是特定于体系结构的,这意味着您必须针对32位(x86)或64位(x64)重新编译它。
如果C++/CLI DLL与Visual Studio的体系结构不同,则设计器无法加载它。
尝试为x86编译以使用设计模式。

t0ybt7op

t0ybt7op2#

#pragma once
using namespace System;
using namespace System::Windows::Forms;
namespace wfext {
    public ref class IntTextBox : TextBox {
        String^ origin = "0";
        //A string to return to if the user-inputted text is not an integer.
    public: IntTextBox(){
        this->Text = "0";
        TextChanged += gcnew EventHandler(this, &IntTextBox::IntTextBox_TextChanged);
    }
    private: void IntTextBox_TextChanged(Object^ sender, EventArgs^ e){
        int temp;
        if (int::TryParse(this->Text, temp)){   //If the value of "Text" can be converted into an integer.
            origin = this->Text;
            //"Save" the changes to the "origin" variable.
        }
        else{
            this->Text = origin;
            //Return to the previous text value to remove invalidity.
        }
    }
    };
}

相关问题