visual c++ copy textbox content - c++

how to copy textbox->Text content in a char array?
i m working in vc++.

Use CWnd::GetWindowText()
CString str;
CWnd* pWnd = GetDlgItem(IDC_WHATEVER);
pWnd->GetWindowText(str);
Puts the contents of the control into the CString or you can use the array version:
TCHAR sz[10];
int nRet = pWnd->GetWindowText(sz, 10);

Your query is unclear, so I'll have to assume things.
Assuming you are using MFC, add a control type variable to your edit box (say m_Edit), and use m_Edit.GetWindowText() to get the text.
Or if you're using plain Win32, use the GetWindowText() Win32 API.
On an additional note, like another user pointed out, stop using things like fixed-size character arrays to store strings if you are using c++. Use something like std::string or use CString if you're using MFC. By doing so, you can manipulate strings much easily and your code will be less error prone.
Cheers, Rajesh. MVP, Visual C++

You can also try like this.....
CString csTbxName;
GetDlgItemText(IDC_EDIT1,csTbxName);
const char* pchTbxName = csTbxName.GetBuffer();
char chTbxNameDup[5000];
ZeroMemory(chTbxNameDup,5000);
if(csTbxName.GetLength() < 5000)
{
memcpy(chTbxNameDup,(void*)pchTbxName,csTbxName.GetLength());
}

Related

MFC C++ CListBox get selected item

First let me say that I've been searching for a solution for couple of days now...
I'm trying to get selected item for ListBox. This is my code:
CListBox * pList1 = (CListBox *)GetDlgItem(IDC_LIST1);
CString ItemSelected;
// Get the name of the item selected in the Sample Tables list box
// and store it in the CString variable declared above
pList1->GetText(pList1->GetCurSel(), ItemSelected);
MessageBox(ItemSelected, "TEST", MB_OK);
Now when i try this i get an error message saying "The Parameter is incorect"
Your code looks OK except error handling. Also MessageBox parameters look incorrect. The first parameter should be of type HWND. I believe that this is the root cause of your problems. Use MFC standard AfxMessageBox instead:
CListBox * pList1 = (CListBox *)GetDlgItem(IDC_LIST1);
int nSel = pList1->GetCurSel();
if (nSel != LB_ERR)
{
CString ItemSelected;
pList1->GetText(nSel, ItemSelected);
AfxMessageBox(ItemSelected);
}
If the CListBox is in single selection mode, the CListBox::GetCurSel will return the selected index.
If the CListBox is in multi-selection mode, you should use CListBox::GetSelItems which will return a list of indices.
You cannot mix'n'match the functions.
And always check return codes (as others already wrote).
If You already have a data member MyList(of classCListBox) :
int nSel = MyList.GetCurSel();
CString ItemSelected;
if (nSel != LB_ERR)
{
MyList.GetText(nSel, ItemSelected);
}
CWnd class has a MessageBox function which does not need a HWND parameter. But yes, AfxMessageBox is a little bit more easier to use and can be called anywhere in the MFC code without having a CWnd-derived object. And a beside note: if call a WinAPI function inside MFC code (not needed here, but possible in other cases) it's good to prepend it with scope resolution operator in order to avoid any confusion, mistake and/or name conflict (e.g. ::MessageBox...).
One possible cause for "invalid parameter" error in OP code is that it uses an ANSI string literal ("TEST") in a UNICODE build configuration. This case, must use an UNICODE string literal (L"TEST") or a little bit better, use _T macro (_T("TEST")) that makes it possible to build in both ANSI and UNICODE configurations.

How to get different language text by GetWindowText?

How to get different language text by GetWindowText?
I have modfying a whiteboard project. When the user type in the whiteboard, the onchange function will called and will show the text in the whiteboard. However, when I type Japanese text (Non system default language) it shows "?" instead. The following is the code spinet for onchange.
void CHBEdit::OnChange()
{
static bool bChanged = true;
CDC *pDC = GetDC();
if (bChanged) {
CString str;
GetWindowText(str);
m_strText = str;
int iStartChar, iEndChar;
GetSel(iStartChar, iEndChar);
CRect rect;
GetWindowRect(&rect);
CFont *Oldfont = (CFont *)pDC->SelectObject(&m_Font);
CSize size = pDC->GetOutputTextExtent(str); //+ "a");
pDC->SelectObject(Oldfont);
SetWindowPos(NULL, 0, 0, size.cx, size.cy, SWP_NOMOVE);
bChanged = false;
SetWindowText(str);
SetSel(iStartChar, iEndChar);
}
else
bChanged = true;
ReleaseDC(pDC);
}
I am really new in C++. I did research and had tried GetwindowTextW with UTF8 unicode, but it still showing "?". Maybe the logic wrong.
I would appreciate it if anyone could give me the solution to show different language text in the whiteboard. Thank you.
GetWindowTextW is the right way. Windows uses UTF16 Unicode standard, with wchar_t wide string. UTF8 standard is commonly used with Linux and internet. You may need UTF16/UTF8 conversion only when exporting/importing data to other systems.
If you create a new MFC project it will be setup in Unicode and MFC functions will default to Unicode. Example:
//UNICODE project:
CString str;
GetWindowText(str);
MessageBox(str);
If project is Unicode, this will will work in Japanese and all other languages.
If you are working with a legacy MFC project which is stuck in in ANSI mode and you can't change it, use the following fix:
//ANSI project:
CStringW str;
GetWindowTextW(str);
MessageBoxW(str);

How to copy data from a stream to a LPCTSTR variable?

I'm absolutely new to programming. I searched for this question online but couldn't find it anywhere
I'm trying to create window based MFC application using Visual studio 13. I have implemented an OpenFileDialog and obtained the path and file name in a stream.
Now I need to make it appear in a edittext box using the function SetWindowText. It accepts parameter of type LPCTSTR. So how do I make the conversion or Is there any other better approach for this problem?
Thanks in advance!
Don't mess around with dynamic allocation here. Simply get the string of the stream and put it into a CString.
It has an operator LPCTSTR for this purpose.
#include <atlstr.h> //CString
CString csText;
.SetWindowText(csText);

MFC C++ VS 2010 : Edit Box to accept only alphabets, backspace and spaces

As mentioned in the title, I am currently using VS 2010 C++ , MFC application for my project. Currently new to programming.
I am currently asked to create an edit box to accept names, full names, e.g "Lee Roy Long". I have looked through many other websites but I am confused with which method should I use to do it.
Is there any examples or a guide to how to go about this?
EDIT: I have another question aside from this solved one [ Cannot Post new questions due to the "restrictions"], I am currently using the same edit box to add new names as strings into the SQLite database. I am currently having some trouble converting CString to string
vector<int> userSerialNumber;
vector<string> userName;
vector<int> userID;
vector<int> userTrainingImagesNo;
Program starts here:
CString str,text;
CString Lone = _T("MEEP"); // This one converts it succesffuly...
string ss((CStringA(Lone)));/Only works for declared CStrings?
CEdit* editBox = (CEdit*)GetDlgItem(IDC_EDIT1);
editBox->GetWindowText(str);
Adding the user's input from above into the program below.
userSerialNumber.push_back(newserialnumber);
userID.push_back(newserialnumber);
userName.push_back(ss);
userTrainingImagesNo.push_back(Img);
I have referred to many websites on how to convert CStrings to strings, but none of them worked, including this one.
As I debug the program, the conversion between CString and string did not work as I get "" for string, which causes the database to update a blank "".
CString str = "name";//Name CString gotten from EditBox
std::string newname = ""; //After typing many conversion methods, results ""
Is there something that I did not notice regarding this ?
You can filter the keystrokes going into the edit control by deriving a class from CEdit and handling the WM_CHAR message in your derived class. To accept a key pass it along to CEdit::OnChar, to reject a key simply return without calling the CEdit function.
To connect the edit control to your code you use a standard MFC subclassing technique. Right-click on the control and create a control member variable (a CEdit) in the parent window. Then edit to change the variable from a CEdit to a CYourDerivedCEdit.
There is a tutorial about this and a sample project at http://www.flounder.com/validating_edit_control.htm
As an alternative to trapping each character, you can handle the CWnd::OnKillFocus event for the edit box and interrogate the value once. Validating can be done by using CString::SpanExcluding with numbers and any other character that should not be in the resulting string. For example,
CString stringEnteredByUser = _T("Lee Roy Long");
CString validatedString = stringEnteredByUser.SpanExcluding("0123456789");
if (stringEnteredByUser != validatedString)
AfxMessageBox(_T("Invalid string"), MB_OK);
The 'stringEnteredByUser' variable should contain the string entered by the user. In this example, using SpanExcluding will tell you if they've entered a number. The returned string from the call (validatedString) will not match the string the user typed (stringEnteredByUser) if they've entered a character that is invalid (ie. the character is within the list provided to the SpanExluding call).
If the validatoin fails, simply force the focus back to the edit box.
I'm assuming you know some basic event coding.
Use the Textbox.textchanged event.
Also research ASCII and its conversion (asc function.)
If you need any more help, comment below.
Good luck!

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

Is it possible to manipulate .net controls from native code? Particularly, 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;
}