(1)创建ActiveX控件
使用MFC ActiveX ControlWizard创建一个名为Test的ActiveX控件工程,使用默认设置
(2)画时钟
1.设置时钟控件的大小
CTestCtrl::CTestCtrl()
{ InitializeIIDs(&IID_DTest, &IID_DTestEvents);
// TODO: Initialize your control's instance data here.
SetInitialSize(200,230);//设置空间初始尺寸的大小
}
2. 在OnDraw函数中画时钟
void CTestCtrl::OnDraw( CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
// TODO: Replace the following code with your own drawing code.
pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH)));
// pdc->Ellipse(rcBounds);//注释掉
pdc->SetBkMode(TRANSPARENT);// 设置背景透明
CTime time; time = CTime::GetCurrentTime();//获取系统时间
double pi = 3.14159265; int cx = rcBounds.left + 100;//时钟的中心位置X坐标
int cy = rcBounds.top + 100;//时钟的中心位置Y坐标
for (int i = 0; i<60;i++)
{ int x = cx + 80*cos(i*pi/30) + 0.5;
int y = cy + 80*sin(i*pi/30) + 0.5;
if (i%5 == 0)
{
pdc->Ellipse(x-3,y-3,x+3,y+3); //大刻度
}
else
{
pdc->Ellipse(x-1,y-1,x+1,y+1);//小刻度
}
}
CString strN = time.Format("%H:%M:%S");//时间写入字符串
//输出字符串,在时钟下面以数字方式显示时间
pdc->TextOut(rcBounds.left +70,rcBounds.top +200,strN);
//下面将使用三种不同粗细的画笔来画出时钟的时针,分针和秒针
CPen pen1(PS_SOLID,4,RGB(0,0,0));//时针
CPen pen2(PS_SOLID,2,RGB(0,0,0));//分针
CPen pen3(PS_SOLID,1,RGB(0,0,0));//秒针
//根据当前时间计算时针的终点位置(x1,y1)
int x1 = cx + 40*cos((time.GetHour()-3)*pi/6 + (time.GetMinute()/12)*pi/30) + 0.5;
int y1 = cx + 40*sin((time.GetHour()-3)*pi/6 + (time.GetMinute()/12)*pi/30) + 0.5;
//根据当前时间计算分针的终点位置(x2,y2)
int x2 = cx + 60*cos((time.GetMinute()-15)*pi/30) + 0.5;
int y2 = cx + 60*sin((time.GetMinute()-15)*pi/30) + 0.5;
//根据当前时间计算秒针的终点位置(x3,y3)
int x3 = cx + 70*cos((time.GetSecond()-15)*pi/30) + 0.5;
int y3 = cx + 70*sin((time.GetSecond()-15)*pi/30) + 0.5;
CPen * pOldPen = pdc->SelectObject(&pen1);
pdc->MoveTo(cx,cy);//画出时针
pdc->LineTo(x1,y1);
pdc->SelectObject(&pen2);
pdc->MoveTo(cx,cy);//画出分针
pdc->LineTo(x2,y2);
pdc->SelectObject(&pen3);
pdc->MoveTo(cx,cy);//画出秒针
pdc->LineTo(x3,y3);
pdc->SelectObject(pOldPen);
}
*****因为使用是sin cos 所以要加一个头文件 #include <MATH.H>**********
(3)为了让时钟跑起来,添加计时器。(添加消息映射函数WM_CLOSE,WM_TIMER,WM_CREATE)
添加方法:右键CTestCtrl类 选择Add Window Message Handler 双击WM_CLOSE,WM_TIMER,WM_CREATE 点击OK 完成!
(4)三个消息映射的实现
void CTestCtrl::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
InvalidateControl();//重画控件,相当于调用OnDraw函数
COleControl::OnTimer(nIDEvent);
}
int CTestCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (COleControl::OnCreate(lpCreateStruct) == -1) return -1;
// TODO: Add your specialized creation code here
SetTimer(1,1000,NULL);//设置定时器
return 0;
}
void CTestCtrl::OnClose()
{
// TODO: Add your message handler code here and/or call default
KillTimer(1);//释放计时器
CWnd::OnClose();
}
(5)编译 Build(F7) Debug版下 在当前项目的debug下生成一个.ocx文件 (***已经注册成功,如果没有注册成功,就自己注册下)
(6)调用时钟控件(我是在VC下调用的,VS 也差不多)
随意新建一个MFC Dialog类
1. 右键 对话框空白处, 选择Insert ActiveX Control
2. 选择你创建的时钟控件(Test Control)
3. 然后直接运行就OK了 (简单的时钟就做好了)