EyeCtrl.cpp

 // EyeCtrl.cpp : implementation file
//

#include "stdafx.h"
#include "OO.h"
#include "EyeCtrl.h"
#include <math.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

BEGIN_MESSAGE_MAP(CEyeCtrl, CStatic)
//{{AFX_MSG_MAP(CEyeCtrl)
ON_WM_PAINT()
ON_WM_TIMER()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

CEyeCtrl::CEyeCtrl() {
initialized = false;
}

CEyeCtrl::~CEyeCtrl() {
if (imagedc) DeleteDC(imagedc);
if (bitmapHandle) DeleteObject(bitmapHandle);
DeleteObject(blackPen);
DeleteObject(whiteBrush);
DeleteObject(blackBrush);
}

void CEyeCtrl::Init() {
initialized = true;

RECT client;
GetClientRect(&client);
height = client.bottom;
width = client.right;

RECT bb;
GetWindowRect(&bb);
Sx = bb.left;
Sy = bb.top;

if (!(bitmapHandle = CreateCompatibleBitmap(::GetDC(GetSafeHwnd()), client.right, client.bottom))) return;

//Create a DC for the image
if (!(imagedc = CreateCompatibleDC(0))) return;
SelectObject(imagedc, bitmapHandle);

whiteBrush = CreateSolidBrush(0xFFFFFF);
blackBrush = CreateSolidBrush(0);
blackPen = CreatePen(PS_SOLID, 0, 0);

HBRUSH tempBrush = CreateSolidBrush(GetSysColor(COLOR_3DFACE));
SelectObject(imagedc, tempBrush);
HPEN tempPen = CreatePen(PS_NULL, 0, 0);
SelectObject(imagedc, tempPen);
Rectangle(imagedc, 0, 0, client.right+1, client.bottom+1);
SelectObject(imagedc, whiteBrush);
SelectObject(imagedc, blackPen);
DeleteObject(tempBrush);
DeleteObject(tempPen);


SetTimer(73, 10, 0); //Refresh approximately every ten milliseconds
}

void CEyeCtrl::OnPaint() {
Refresh();
ValidateRect(NULL);
}

void CEyeCtrl::Refresh() {
if (!initialized) Init();
POINT scrPos;
::GetCursorPos(&scrPos);

double Px = scrPos.x - Sx - width/2L;
double Py = scrPos.y - Sy - height/2L;

double k,h,a,b,m; //This is where the math happens
m = Py/Px; //Slope of line from eye to point
a = width/2L; //X radius of eye
b = height/2L; //Y radius of eye
h = (2*a*b)/(3*sqrt((m*m)*(a*a)+(b*b)));//X centre of Pupil
k = m*h; //Y centre of Pupil

if (Px < 0) { h = -h; k = -k; }
if (fabs(h) > fabs(Px)) { h = Px; k = Py; }

SelectObject(imagedc, whiteBrush);
Ellipse(imagedc, 0, 0, width, height);
SelectObject(imagedc, blackBrush);
Ellipse(imagedc,
(long)(h + width/3L),
(long)(k + height/3L),
(long)(h + width*2L/3L),
(long)(k + height*2L/3L));

BitBlt(::GetDC(GetSafeHwnd()), 0, 0, width, height, imagedc, 0, 0, SRCCOPY);
}

void CEyeCtrl::OnTimer(UINT nIDEvent) {
if (nIDEvent == 73) Refresh();
CStatic::OnTimer(nIDEvent);
}

Project Homepage: