开发者

How to set the text in a TextBox control from native code?

Is it possible to manipulate .net controls from native code? Particula开发者_StackOverflow社区rly, I'd like to set the text of a TextBox from some native code. I want it done this way to keep the business logic separated from the user interface, but it is precisely the native code which only knows how to appropriately format the data (some bytes received within a protocol).

I know I could get the window handle through the Handle property, but once there, how would I call the desired method?

Is string handling my only option? Should the native code build up the message to be displayed on the control?


The "native" way of setting the text on a textbox is to send the textbox the WM_SETTEXT message:

// handle is initialized from TextBox::Handle
PostMessage(handle, WM_SETTEXT, 0, _T("Some text"));

Read up on PostMessage and SendMessage, too. Depending on how you allocate and build up the text, you may need to use SendMessage to avoid deallocating prematurely.


If you want to keep your business logic separated from your user interface, and some of your business logic is in native code, then it would be a really good idea not to change any GUI content from the native code directly, because it is exactly the opposite of what you want to achieve. Better try to write some kind of wrapper method in C++/CLI to call the native data format routine from there, making it available for your use in your GUI code.

If you really want to make calls from native code to managed code, you can declare a (native!) static method in C++/CLI which calls a managed method. You can pass a function pointer to such a method to a lower layer of your program (for example, your native C++ layer), which can be called from there.

Something along the lines of:

// the native code layer:
// "Callbacks.h"
void (*_myNativeCallback)();
void InitCallback(void (*myNativeCallback)())
{
   _myNativeCallback=myNativeCallback;
}
// now you can use _myNativeCallback within your native code


// the C++/CLI layer:
#include "Callbacks.h"
//...
static void MyNativeCallback()
{
    ManagedClass::StaticMethod();
}
InitCallback(MyNativeCallback);

In ManagedClass::StaticMethod, you have access to your .NET code and you should not have any problems to manipulate a TextBox of any form you can reach from there. If you have to convert a native string to a System::String, you may find this code snippet helpful:

inline System::String StdToSysString(const std::string &s)
{
    return gcnew System::String(s.c_str());
}

And the other way round (Ansi code page assumed):

inline std::string SystemToStdString(System::String ss)
{
    using namespace System::Runtime::InteropServices;
    const char* chars = 
      (const char*)(Marshal::StringToHGlobalAnsi(ss)).ToPointer();
    std::string s = chars;
    Marshal::FreeHGlobal(System::IntPtr((void*)chars));
    return s;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜