MFC之控制元件和Cstring型別轉換篇
阿新 • • 發佈:2019-01-03
1.開啟檔案
CFileDialog dlg(TRUE,NULL,NULL,OFN_ALLOWMULTISELECT,_T("All File |*.*|Jpeg File(*.jpg;*.jpeg;*.jpe)|*.jpg;*.jpeg;*.jpe|Windows(*.bmp)|*.bmp|CompuServe GIF(*.gif)|*.gif|Png檔案(*.png)|*.png||"),this); dlg.m_ofn.lpstrTitle =_T("Open"); if(dlg.DoModal() == IDOK) { m_FileStr =dlg.GetFileName();//檔名 strFilePath = dlg.GetPathName();//路徑 }
2.控制元件顯示
Static Text
Edit Control
SetDlgItemText(IDC_Name,m_FileStr); //m_filestr為CString
listBox
CListBox* pListBox;
pListBox = (CListBox*) GetDlgItem(IDC_ListShow);
pListBox->AddString(str);
pListBox->DeleteString(index);//刪除指定index
pListBox->ResetContent();//清空
從控制元件中獲取資料
Static Text
CEdit* pBoxOne;
CString str;
pBoxOne = (CEdit*) GetDlgItem(IDC_Opacity);
pBoxOne-> GetWindowText(str);
ListBox
CListBox* pListBox;
pListBox = (CListBox*) GetDlgItem(IDC_ListShow);
int index = pListBox->GetCurSel();
if (index>=0)
{
pListBox->GetText(index,str);
}
3.CString的轉換
UTF8下
Cstring To Int
_ttoi(str)
Int to CString
int num = 100;
str.Format(_T("%d"),num);
Char To Cstring
TCHAR MuName[100];
char tchar[100];
MultiByteToWideChar(CP_ACP, 0,tchar , -1, MuName, 100);
str.Format(_T("%s"),MuName);
Cstring To Char
void CStringToChar(CString str,char* dst = NULL){
char* src;
int len = WideCharToMultiByte( CP_UTF8 , 0 , str , str.GetLength() , NULL , 0 , NULL , NULL );
src = (char*)malloc(len+1*sizeof(char*));
len = WideCharToMultiByte( CP_UTF8 , 0 , str , str.GetLength() , src , len +1 , NULL ,NULL );
src[len] = 0;
if (dst!=NULL)
{
strcpy(dst,src);
}
free(src);
}
還用一些其他函式
Char To Wchar_t
void CharToWChar_t(char* src,wchar_t* dst){
DWORD dwNum = MultiByteToWideChar(CP_ACP,0,src,-1,NULL,0);
int nlen = MultiByteToWideChar (CP_ACP, 0, src, -1, dst, dwNum+10);
dst[nlen] = 0;
}
十六進位制轉十進位制
int CharHex16ToInt(char* str)
{
int len = strlen(str);
int k = 1,sum = 0;
if (len>2&&str[0]=='0'&&str[1]=='x')
{
for (int i = len-1; i>=2; i--,k*=16)
{
int tmp = 0;
if (str[i]>='0'&&str[i]<='9')
{
tmp = str[i]-'0';
}else if (str[i]>='A'&&str[i]<='F')
{
tmp = str[i]-'A'+10;
}else if (str[i]>='a'&&str[i]<='f')
{
tmp = str[i]-'a'+10;
}
sum += tmp*k;
}
}
else
{
for (int i = len-1; i>=0; i--,k*=10)
{
int tmp = 0;
if (str[i]>='0'&&str[i]<='9')
{
tmp = str[i]-'0';
}
sum += tmp*k;
}
}
return sum;
}