今度はボタンを選択状態にして (マウスでクリックして)、 ClassWizard をたちあげて、メッセージマップを見る。
Button1をクリックすると,メンバ関数の追加のダイアログがでるので,OKボタンをクリックすると,次のようなOnButton1()イベントハンドラが表示されるので,
の中に以下のようなコードを記述する。
=======================================================
void CDialog1Dlg::OnButton1()
{
CWnd
h = GetDlgItem(IDC_PICTURE);
CDC
pDC=h-
GetDC();
CRect r; // rは長方形クラスのオブジェクト。長方形データを格納する場所を設定
h-
GetClientRect(&r); // クライアント領域を r に格納
int pw,ph;
pw=r.right; // 長方形rの右はた。つまり幅
ph=r.bottom;
//目盛線をシアンで描く。
CPen p(PS_SOLID,1,RGB(0,255,255)); // シアンはgreenとblue
CPen
oldp=pDC-
SelectObject(&p);
//縦の目盛線群を描く
double x;
double dx=pw/20; // 目盛線の間隔
for(x=0; x
=pw; x+=dx){
pDC-
MoveTo(int(x),0);
pDC-
LineTo(int(x),ph);
}
//横の目盛線群を描く
double y;
double dy=ph/20; // 目盛線の間隔
for(y=0; y
=ph; y+=dy){
pDC-
MoveTo(0,int(y));
pDC-
LineTo(pw,int(y));
}
pDC-
SelectObject(oldp);
//x軸を黒い太字で描く
CPen pen(PS_SOLID,2,RGB(0,0,0)); // 2で太字
CPen
oldpen=pDC-
SelectObject(&pen);
int cx,cy; // 中心の座標
cx = pw/2;
cy = ph/2;
pDC-
MoveTo(0,cy);
pDC-
LineTo(pw,cy);
//y軸を黒い太字で描く
pDC-
MoveTo(cx,0);
pDC-
LineTo(cx,ph);
// 使い終わったら、もとのペンに戻す
pDC-
SelectObject(oldpen);
h-
ReleaseDC(pDC);
}
}
=======================================================
グラフの描画
=======================================================
void CDialog1Dlg::OnButton2()
{
CWnd
h = GetDlgItem(IDC_PICTURE);
CDC
pDC=h-
GetDC();
CRect r; // 長方形データを格納する場所を設定
h-
GetClientRect(&r); // クライアント領域を r に格納
int pw,ph;
pw=r.right;
ph=r.bottom;
//ペイントコントロールの幅,高さの中点を原点(xc,yc)とする。
int xc=pw/2, yc=ph/2;
//1目盛りの値をdx,dyとする.
double dx = pw/20.0, dy = ph/20.0;
double x,y;
int xg,yg;
//グラフを赤で描く。クリッピング領域を長方形の大きさに設定する。
CRgn s;
s.CreateRectRgn(0,0,pw,ph);
pDC-
SelectClipRgn(&s);
for(x=-5;x
=5;x+=0.01){
y = x*x;
xg = xc + int(dx*x);
yg = yc - int(dy*y);
pDC-
SetPixel(int(xg),int(yg),RGB(255,0,0));
}
s.DeleteObject();
h-
ReleaseDC(pDC);
}
=======================================================
| CWnd |
| CDC |
| CPen |
| myPen- |
| pDC- |
| delete myPen; // myPenを消去 |