How to use a variable inside a _T wrapper?
I want to make the hostname part of this string to be variable.. Currently, it is only fix to this URL:
_T(" --url=http://www.myurl.com/ --out=c:\\current.png");
I want to make something like this, so the URL is changeable..
_T(" --url=http://www." + myurl + "/ --out=c:\\current.png");
update. Below is my latest attempt:
CString one = _T(" --url=http://www.");
CString two(url->bstrVal);
CString three = _T("/ --out=c:\\current.png");
CString full = one + two + three;
ShellExecute(0, 开发者_开发技巧
_T("open"), // Operation to perform
_T("c:\\IECapt"), // Application name
_T(full),// Additional parameters
0, // Default directory
SW_HIDE);
The error is : Error 1 error C2065: 'Lfull' : undeclared identifier c:\test.cpp
It doesn't work because the _T()
macro works only with constant string literals. The definition for _T()
looks something like this:
#ifdef UNICODE
#define _T(str) L##str
#else
#define _T(str) str
Since you're apparently compiling in Unicode mode, _T(full)
expands to Lfull
, which is obviously not what you want.
In your case, just pass in full
without the _T()
macro since CString
defines a conversion operator to a const wchar_t*
in Unicode mode, and const char*
in non-Unicode mode.
ShellExecute(0, _T("open"), _T("c:\\IECapt"), full, 0, SW_HIDE);
Note that standard C++ also provides a std::string
type and a std::wstring
type which does pretty much what CString
does, so MFC isn't actually required for string manipulation. std::string
does not provide a conversion operator, but does provide access to the underlying C-style string via c_str()
.
Your latest attempt will work if you lose _T() from around "full" in the call to ShellExecute. The CString will return the correct pointer. Job done.
In addition though... You should just lose the _T() stuff completely. If you're going to do things like reference url->bstrVal directly (which is Unicode, no matter what you're compiling for) then your code will only work as Unicode.
There's very little reason anymore to compile the same project for both Unicode and ANSI these days. The _T() stuff was created to address both modes "easily". But unless you're targeting Win95/98/ME, you can just go Unicode and clean up your code. Unicode is faster too, because the Windows API and the Kernel is Unicode internally. All ANSI APIs start by converting string parameters to Unicode first, and then calling their wide-char counterpart.
So no _T, TCHAR, etc. Use things like this instead:
PWSTR psz = L"my unicode string";
CString s = L"my other string, yay!";
In addition to what In silico said, CString::Format makes this code a lot more readable:
CString full;
full.Format(_T(" --url=http://www.%s/ --out=c:\\current.png"), url->bstrVal));
精彩评论