tags:

views:

275

answers:

2

I'm trying to set the text of a textfield using the Carbon API like this:

ControlID editId = {'EDIT', 3};
ControlRef ctrl;
GetControlByID(GetWindowRef(), &editId, &ctrl);
CFStringRef title = CFSTR("Test");   
OSErr er = SetControlData(ctrl, kControlEntireControl, kControlEditTextTextTag, CFStringGetLength(title), title);
CFRelease(title);

I'm using the C++ code template of XCode, so GetWindowRef() is a call to the predefined TWindow class. The OSErr return value gives me noErr, but my textfield only contains garbage. It doesn't matter if I set the attribute of my textfield to Unicode or not.

Any ideas what is wrong here?

+2  A: 

What does the GetControlID(...) return? Is it noErr?

As a ControlRef is also a HIViewRef, you can also use the function:

HIViewSetText to set the text. This is documented to work with functions that accept kControlEditTextCFStringTag.

By the way, the line you wrote:

CFRelease(title);

Will cause problems. One should only release objects that have been made using functions that have Create or Copy in the API name. You'll want to read: "Introduction to Memory Management Programming Guide for Core Foundation" -- search in the Xcode documentation.

Lyndsey Ferguson
Yes it does return noErr. thx for the CFRelease hint
jn_
Does the HIViewSetText work? It seems a lot simpler to call than the calls currently being used.
Lyndsey Ferguson
A: 

Finally this did the trick:

SetControlData(ctrl, kControlEditTextPart, kControlStaticTextCFStringTag, sizeof(title), &title);

Since this seems to be very old API, a better way seems to be:

HIViewSetText(ctrl, title);

Thx to Lyndsey for the hints.

jn_