Проблемы с чтением из текстового поля в C # от Win32 C ++ программы? - PullRequest
0 голосов
/ 08 сентября 2011

Я пытаюсь прочитать из формы C #, которую я создал, и передать ее в мое приложение win 32. Проблема в том, что я всегда получаю нулевую строку wstring вместо того, чтобы получать текст из textbox.i создаю ссылку на файл dll формы C # из моей программы на c ++. Я знаю, что проблема в части C #, поскольку я отлаживал ее и обнаружил, что она сама никогда не получает значение из текста. Поскольку я впервые использую C #, я не знаю, что не так, я вставляю свой код C # ниже.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace UpdaterForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            this.Text=textBox1.Text;
        }

        public String textbox1
        {
            get{
                  return textBox1.Text;
            }
        }


        public String textbox2
        {
            get
            {
                return textBox2.Text;
            }
        }

        public String textbox3
        {
            get
            {
                return textBox3.Text;
            }
        }

    }
}





using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows.Forms;

namespace UpdaterForm
{
    public class UpdaterForm
    {
        public string PickText( )
        {
            Form1 form = new Form1();
            String text1;
            String text2;
            String text3;

            Application.Run(form);
            text1 = form.textbox1;
            text2 = form.textbox2;
            text3 = form.textbox3;
            form.Dispose();
            string text = text1 + "." + text2 + "." + text3;
            return text;
        }
    }
}

вот код с ++

#include <string>

class UpdaterFormClient
{
 private:

    void* ref;

    void alloc();
    void free();
    wchar_t * pick();

 public:

    UpdaterFormClient();
    ~UpdaterFormClient();

    void picker(std::wstring &);
};

файл cpp

#include <windows.h>
#include "UpdaterFormClient.h"
#include <vcclr.h>

using namespace System;
using namespace System::Runtime::InteropServices;

#pragma unmanaged

UpdaterFormClient::UpdaterFormClient()
{
 alloc();
}

UpdaterFormClient::~UpdaterFormClient()
{
 free();
}

void UpdaterFormClient::picker(std::wstring &text1)
{
 wchar_t *p;

 p = pick();
 text1 = p;
 delete [] p;
}

#pragma managed
#using <mscorlib.dll>
#using <..\\..\\UpdaterForm\\UpdaterForm\\bin\\debug\\UpdaterForm.dll>

void UpdaterFormClient::alloc()
{
 GCHandle gch;
 UpdaterForm::UpdaterForm ^obj;

 obj = gcnew UpdaterForm::UpdaterForm();
 gch = GCHandle::Alloc(obj);
 ref = GCHandle::ToIntPtr(gch).ToPointer();

 return;
}

void UpdaterFormClient::free()
{
 IntPtr temp(ref);
 GCHandle gch;

 gch = static_cast<GCHandle>(temp);
 gch.Free();
}

wchar_t * UpdaterFormClient::pick()
{
 IntPtr temp(ref);
 String ^text1;
 wchar_t *ret;
 GCHandle gch;
 UpdaterForm::UpdaterForm ^obj;

 gch = static_cast<GCHandle>(temp);
 obj = static_cast<UpdaterForm::UpdaterForm ^>(gch.Target);
 text1 = obj->PickText();
 ret = new wchar_t[text1->Length + 1];

 interior_ptr<const wchar_t> p1 = PtrToStringChars(text1);
 pin_ptr<const wchar_t> p2 = p1;
 wcscpy_s(ret, text1->Length + 1, p2);

 return ret;
}

1 Ответ

0 голосов
/ 09 сентября 2011

Программы Windows не работают так, как вы ожидаете.

Вы запускаете цикл приложения Application.Run(form), а затем, когда он заканчивается, вы пытаетесь получить значения текстового поля.

Вы не можете сделать это в программе Windows.

Application.Run(form) будет блокироваться, пока окно не закроется или цикл сообщений не закончится.

Следовательно, вам нужно переместить код, связанный с вашими текстовыми полями, в вашу форму.

Поместите кнопку в форму и вставьте код текстового поля в событие нажатия кнопки. Используйте вызов MessageBox.Show для отображения того, что было введено.

Я попытался продемонстрировать это здесь (вам нужно более подробно объяснить часть c ++):

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace UpdaterForm 
{ 
    public partial class Form1 : Form 
    { 
        public Form1() 
        { 
            InitializeComponent(); 
        } 

        private void Form1_Load(object sender, EventArgs e) 
        { 

        } 

        private void label1_Click(object sender, EventArgs e) 
        { 

        } 

        private void button1_Click(object sender, EventArgs e) 
        { 
            String text1 = textBox1.Text;  
            String text2 = textBox2.Text;  
            String text3 = textBox3.Text;  
            string text = text1 + "." + text2 + "." + text3; 
            MessageBox.Show(text);           
        } 
    } 
} 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

using System.Windows.Forms; 

namespace UpdaterForm 
{ 
    public class UpdaterForm 
    { 
        public string PickText( ) 
        { 
            Form1 form = new Form1(); 

            try {
              Application.Run(form); 
            } finally {
              form.Dispose();
            } 
        } 
    } 
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...