MFC_vc++_ 控件的位置、大小获取、与控件移动、获取屏幕分辨率,获取对话框窗体大小及其屏幕坐标

用CWnd类的函数MoveWindow()或SetWindowPos()可以改变控件的大小和位置。

void MoveWindow(int x,int y,int nWidth,int nHeight);
void MoveWindow(LPCRECT lpRect);
第一种用法需给出控件新的坐标和宽度、高度;
第二种用法给出存放位置的CRect对象;
例:

CWnd *pWnd;
pWnd = GetDlgItem( IDC_EDIT1 ); //获取控件指针,IDC_EDIT1为控件ID号
pWnd->MoveWindow( CRect(0,0,100,100) ); //在窗口左上角显示一个宽100、高100的编辑控件

SetWindowPos()函数使用更灵活,多用于只修改控件位置而大小不变或只修改大小而位置不变的情况:
BOOL SetWindowPos(const CWnd* pWndInsertAfter,int x,int y,int cx,int cy,UINT nFlags);
第一个参数我不会用,一般设为NULL;
x、y控件位置;cx、cy控件宽度和高度;
nFlags常用取值:
SWP_NOZORDER:忽略第一个参数;
SWP_NOMOVE:忽略x、y,维持位置不变;
SWP_NOSIZE:忽略cx、cy,维持大小不变;

方法也适用于各种窗口
例:

CWnd *pWnd;
pWnd = GetDlgItem( IDC_BUTTON1 ); //获取控件指针,IDC_BUTTON1为控件ID号
pWnd->SetWindowPos( NULL,50,80,0,0,SWP_NOZORDER | SWP_NOSIZE ); //把按钮移到窗口的(50,80)处
pWnd = GetDlgItem( IDC_EDIT1 );
pWnd->SetWindowPos( NULL,0,0,100,80,SWP_NOZORDER | SWP_NOMOVE ); //把编辑控件的大小设为(100,80),位置不变
pWnd = GetDlgItem( IDC_EDIT1 );
pWnd->SetWindowPos( NULL,0,0,100,80,SWP_NOZORDER ); //编辑控件的大小和位置都改变

获取屏幕分辨率

//下边两个函数获取的是显示屏幕的大小,但不包括任务栏等区域
int cx = GetSystemMetrics(SM_CXFULLSCREEN);
int cy = GetSystemMetrics(SM_CYFULLSCREEN);

//下边这两个函数获取的是真正屏幕的大小:屏幕分辨率
int nWidth=GetSystemMetrics(SM_CXSCREEN);  //屏幕宽度    
int nHeight=GetSystemMetrics(SM_CYSCREEN); //屏幕高度
CString strScreen;
strScreen.Format(L"%d,%d",nWidth,nHeight);
MessageBox(strScreen);

获取对话框窗体大小及其屏幕坐标

//对话框窗体大小及其屏幕坐标
CRect rectDlg;
//法1:
GetClientRect(rectDlg);//获得窗体的大小

//法2:
GetWindowRect(rectDlg);//获得窗体在屏幕上的位置
ScreenToClient(rectDlg);
CString strDlg;
strDlg.Format(L"%d,%d,%d,%d",rectDlg.left,rectDlg.top,rectDlg.Width(),rectDlg.Height());
MessageBox(strDlg);

获取控件大小及位置

//控件大小和位置txwtech
CRect rectControl;
CStatic *p=(CStatic*)GetDlgItem(IDC_STATIC_TEST);
p->MoveWindow(100,100,100,100); 		//更改控件大小并移动其到指定位置
//法1:
p->GetWindowRect(rectControl);
this->ScreenToClient(rectControl);

//法2:
//GetDlgItem(IDC_STATIC_TEST)->GetClientRect(rectControl);
CString str;
str.Format(L"%d,%d,%d,%d",rectControl.left,rectControl.top,rectControl.Width(),rectControl.Height());
MessageBox(str);

ScreenToClient也就是Screen(屏幕坐标) 到 Client(客户区坐标)的转换。

也就是说这个函数可以把你在屏幕上鼠标的位置转换为你打开的程序的客户区的坐标(位置)。

先获取控件当前位置,再移动

通过+200,-200,或者任意数字的移动

void CMFCApplication1Dlg::OnBnClickedButton1()
{
	// TODO:  在此添加控件通知处理程序代码
	CWnd *pWnd;
	pWnd = GetDlgItem(IDC_LIST1); //获取控件指针,IDC_BUTTON1为控件ID号


	//控件大小和位置txwtech
	CRect rectControl;
	CListCtrl *p = (CListCtrl*)GetDlgItem(IDC_LIST1);
	//p->MoveWindow(100, 100, 100, 100); 		//更改控件大小并移动其到指定位置
	
	p->GetWindowRect(rectControl);
	this->ScreenToClient(rectControl);//屏幕坐标转成用户坐标
	pWnd->SetWindowPos(NULL, rectControl.left-200, rectControl.top+200, rectControl.Width(), rectControl.Height(), SWP_NOZORDER); //编辑控件的大小和位置都改变


	CString str;
	str.Format(L"%d,%d,%d,%d", rectControl.left, rectControl.top, rectControl.Width(), rectControl.Height());
	MessageBox(str);
}

猜你喜欢

转载自blog.csdn.net/txwtech/article/details/108550903