웹페이지 긁어서 타이틀 뿌려주는 소스

 $file = @fopen( $url, “r”);
   if (!$file)
   {
     echo “usage $PHP_SELF?url=<the url you want to test>”;
     return 0;
   }

   while (!feof($file))
   {
     $text .= fgets($file, 40960);
     // do something
   }
   fclose($file);

   if (eregi( “<title>(.*)</tltle>”, $text, $output))
   {
     // title found
     echo “the document title is [” . $output[1] . “]”;
   }
   else
   {
     // title not found
     echo “the document title not found”;
   }

PHP로 객체지향 프로그래밍 하는 방법

#######################################################################
## Object Oriented Programming in PHP: The way to large PHP projects ##
#######################################################################

This arcticle introduces Object Oriented Programming (OOP) in PHP. I will show you how to code less and better by using some OOP concepts and PHP tricks. Good luck!

Concepts of object oriented programming: There’re differences between authors, I can mention that a OOP language must have:


Abstract data types and information hidding
Inheritance
Polymorphism
The encapsulation is done in php using classes:

<?php

class Something {
   // In OOP classes are usually named starting with a cap letter.
   var $x;

   function setX($v) {
       // Methods start in lowercase then use lowercase to seprate
       // words in the method name example getValueOfArea()
       $this->x=$v;
   }

   function getX() {
       return $this->x;
   }
}

?>

Of course you can use your own nomenclature, but having a standarized one is useful.

Data members are defined in php using a “var” declaration inside the class, data members have no type until they are assigned a value. A data member might be an integer, an array, an associative array or even an object. Methods are defined as functions inside the class, to access data members inside the methods you have to use $this->name, otherwise the variable is local to the method.

You create an object using the new operator:

$obj=new Something;

Then you can use member functions by:

$obj->setX(5);
$see=$obj->getX();

The setX member function assigns 5 to the x datamember in the object obj (not in the class), then getX returns its value: 5 in this case.

You can access the datamembers from the object reference using for example: $obj->x=6; however, this is not a very good OOP practice. I enforce you to set datamembers by defining methods to set them and access the datamembers by using retrieving methods. You’ll be a good OOP programmer if you consider data members inaccesible and only use methods from the object handler. Unfortunately PHP doesn’t have a way to declare a data member private so bad code is allowed.

Inheritance is easy in php using the extend keyword.

<?php

class Another extends Something {
   var $y;
   function setY($v) {
       // Methods start in lowercase then use lowercase to seperate
       // words in the method name example getValueOfArea()
       $this->y=$v;
   }

   function getY() {
       return $this->y;
   }
}

?>

Objects of the class “Another” now has all the data members and methods of the parent class (Something) plus its own data members and methods. You can use

$obj2=new Something;
$obj2->setX(6);
$obj2->setY(7);

Multiple inheritance is not supported so you can’t make a class extend two or more different classes.

You can override a method in the derived class by redefining it, if we redefine getX in “Another” we can’t no longer access method getX in “Something”. If you declare a data member in a derived class with the same name as a data member in a Base class the derived data member “hides” the base class data member when you access it.

You might define constructors in your classes, constructors are methods with the same name as the class and are called when you create an object of the class for example:

<?php

class Something {          
   var $x;

   function Something($y) {
       $this->x=$y;
   }

   function setX($v) {    
       $this->x=$v;          
   }

   function getX() {
       return $this->x;
   }
}

?>

So you can create an object by:

$obj=new Something(6);

And the constructor automatically asigns 6 to the data member x. Constructors and methods are normal php functions so you can use default arguments.

function Something($x=”3″,$y=”5″)

Then:

$obj=new Something(); // x=3 and y=5
$obj=new Something(8); // x=8 and y=5
$obj=new Something(8,9); // x=8 and y=9

Default arguments are used in the C++ way so you can’t pass a value to Y and let X take the default value, arguments are asigned form left to right and when no more arguments are found if the function expected more they take the default values.

When an object of a derived class is created only its constructor is called, the constructor of the Parent class is not called, this is a gotcha of PHP because constructor chaining is a classic feature of OOP, if you want to call the base class constructor you have to do it explicitely from the derived class constructor.It works because all methods of the parent class are available at the derived class due to inheritance.

<?php

function Another() {
   $this->y=5;
   $this->Something();   //explicit call to base class constructor.
}

?>

A nice mechanism in OOP is to use Abstract Classes, abstract classes are classes that are not instanciable and has the only purpose to define an interface for its derived classes. Designers often use Abstract classes to force programmers to derive classes from certain base classes so they can be certain that the new classes have some desired functionality. There’s no standard way to do that in PHP but:

If you do need this feature define the base class and put a “die” call in its constructor so you can be sure that the base class is not instanciable, now define the methods (interface) putting “die” statements in each one, so if in a derived class a programmer doesn’t override the method then an error raises. Furthermore you might need to be sure since php has no types that some object is from a class derived from you base class, then add a method in the base class to identify the class (return “some id”), and verify this when you receive an object as an argument. Of course this doesn’t work if the evil programmer oveerides the method in the derived class but genrally the problem is dealing with lazy programmers no evil ones! Of course is better to keep the base class unreachable from the programmers, just print the interface and make them work!

There’re no destructors in PHP.

Overloading (which is different from overriding) is not supported in PHP. In OOP you “overload” a method when you define two/more methods with the same name but different number or type of parameters (depending upon the language). Php is a loosely typed language so overloading by types won’t work, however overloading by number of parameters doesn’t work either.

It’s very nice sometimes in OOP to overload constructors so you can build the object in different ways (passing different number of arguments). A trick to do something like that in PHP is:

<?php

class Myclass {
   function Myclass() {
       $name=”Myclass”.func_num_args();
       $this->$name();
       //Note that $this->$name() is usually wrong but here
       //$name is a string with the name of the method to call.
   }

   function Myclass1($x) {
       code;
   }
   function Myclass2($x,$y) {
       code;
   }
}

?>

With this extra working in the class the use of the class is transparent to the user:

$obj1=new Myclass(‘1’); //Will call Myclass1
$obj2=new Myclass(‘1′,’2’); //Will call Myclass2

Sometimes this is very nice.


# Polymorphism

Polymorphism is defined as the ability of an object to determine which method to invoke for an object passed as argument in runtime time. For example if you have a class figure which defines a method draw and derived classes circle and rectangle where you override the method draw you might have a function which expects an argument x and then call $x->draw(). If you have polymorphism the method draw called depends of the type of object you pass to the function. Polymorphism is very easy and natural in interpreted languages as PHP (try to imagine a C++ compiler generating code for this case, which method do you call? You don’t know yet which type of object you have!, ok this is not the point). So PHP happily supports polymorphism.

<?php

function niceDrawing($x) {
   //Supose this is a method of the class Board.
   $x->draw();
}

$obj=new Circle(3,187);
$obj2=new Rectangle(4,5);

$board->niceDrawing($obj);    //will call the draw method of Circle.
$board->niceDrawing($obj2);   //will call the draw method of Rectangle.

?>


OOP programming in PHP
Some “purists” will say PHP is not truly an object oriented language, which is true. PHP is a hybrid language where you can use OOP and traditional procedural programming. For large projects, however, you might want/need(?) to use “pure” OOP in PHP declaring classes, and using only objects and classes for your project. As larger and larger projects emerge the use of OOP may help, OOP code is easy to mantain, easy to understand and easy to reuse. Those are the foundations of software engineering. Applying those concepts to web based projects is the key to success in future web sites.

Advanced OOP Techniques in PHP
After reviewing the basic concepts of OOP I can show you some more advanced techniques:


Serializing
PHP doesn’t support persistent objects, in OOP persistent objects are objects that keep its state and funcionality across multiple invocations of the application, this means having the ability of saving the object to a file or database and then loading the object back. The mechanism is known as serialization. PHP has a serialize method which can be called for objects, the serialize method returns a string representation of the object. However serialize saves the datamembers of the object but not the methods.

In PHP4 if you serialize the object to string $s, then destroy the object, and then unserialize the object to $obj you might still access the object methods! I don’t recommend this because (a) The documentation doesn’t guarrantee this beahaviour so in future versions it might not work. (b) This might lead to ‘illusions’ if you save the serialized version to disk and exit the script. In future runs of the script you can’t unserialize the string to an object an expect the methods to be there because the string representation doesn’t have the methods! Summarizing serializing in PHP is VERY useful to save the data members of an object just that. (You can serialize asociative arrays and arrays to save them to disk too).

Example: <?php

$obj=new Classfoo();
$str=serialize($obj);
// Save $str to disk

//…some months later

//Load str from disk
$obj2=unserialize($str)

?>

You have the datamembers recovered but not the methods (according to the documentation). This leads to $obj2->x as the only way to access the data members (you have no methods!) so don’t try this at home.

There’re some ways to fix the problem, I leave it up to you because they are too dirty for this neat article.

Full serialization is a feature I’d gladly welcome in PHP.

Using classes to manipulate stored data
One very nice thing of PHP and OOP is that you can easily define classes to manipulate certain things and the call the appropiate classes whenever you want. Suposse you have a html form where the user selects a product by selecting it’s product ID, you have the data of the products in a database and you want to display the product, show its price, etc etc. You have products of different types, and the same action might have different meanings for different kind of products. For example showing a sound might mean playing it while for some other kind of products might mean to display a picture stored in the database. You might use OOP and PHP to code less and code better:

Define a class product, define which methods the class should have (example display), then define classes for each type of product which extends the product class (class SoundItem, class ViewableItem, etc…) override the methods you define in product in each of this classes make them do what you want. Name the classes according to the “type” column you store in the database for each product a typical product table might have (id,type,price,description,etc etc)… Then in the processing script you can retrieve the type from the database and instanciate an object of the class named type using:

<?php

$obj=new $type();
$obj->action();

?>

This is a very nice feature of PHP, you might then call the display method of $obj or any other method regardless the type of object you have. With this technique you don’t have to touch the processing script when you add a new type of object, just add a class to handle it. This is quite powerful, just define the methods all objects regardless of its type should have, implement them in different ways in different classes and use them for any type of object in the main script, no ifs, no 2 programmers in the same file, eternal happiness. Do you agree programming is easy, mainteinance is cheaper and reusability is real now?

If you command a group of programmers is easy to divide the tasks, each one might be responsable for a type of object and the class that handles it. Internacionalization can be done using this technique, apply the proper class according to a language field selected by the user, etc.


Copying and cloning
When you create an object $obj you can copy the object by doing $obj2=$obj, the new object is a copy (not a reference) of $obj so it has the state $obj had in the moment the assignment was made. Sometimes you don’t want this, you just want to create a new object of the same class as obj, calling the constructor of the new object as if you had used the new statement. This can be done in PHP using serialization and a base class that all other classes must extend.


Entering a danger zone
When you serialize an object you get a string which has a certain format, you may investigate it if you are curious, one of the things the string has is the name of the class (nice!) you may extract it using:

<?php

$herring=serialize($obj);
$vec=explode(‘:’,$herring);
$nam=str_replace(“””,”,$vec[2]);

?>

So suposse you create a class “Universe” and force that all classes must extend universe, you can define a method clone in Universe as:

<?php

class Universe {
   function clone() {
       $herring=serialize($this);
       $vec=explode(‘:’,$herring);
       $nam=str_replace(“””,”,$vec[2]);
       $ret=new $nam;
       return $ret;
   }
}

//Then:

$obj=new Something();
   //Something extends Universe !!
$other=$obj->clone();

?>

What you get is a new object of class Something created the same way as using new, the constructor is called, etc. I don’t know if this is useful for you, but the Universe class which knows the name of the derived class is a nice concept to experiment. The only limit is your imagination.

Note: I’m using PHP4, something I write here may not work in PHP3.

HTML 긁어오는 프로그램 소스

Your first task is to create a Delphi function used to download a file from the Internet. One way of achieving this task is to use the WinInet API calls. Delphi gives us full access to the WinInet API (wininet.pas) which we can use to connect to and retrieve files from any Web site that uses either Hypertext Transfer Protocol (HTTP) or File Transfer Protocol (FTP). I’ve already written an article that describes this technique: Get File From the Net.

Another approach, if you have Delphi 6, is to use the TDownloadURL object. The TDownloadURL object, defined in ExtActns.pas unit, is designed for saving the contents of a specified URL to a file. Here’s the code that uses the TDownloadURL to download the “What’s New and Hot” page from this site.


uses extactns;  // <- must be added //

function Download_HTM(const sURL, sLocalFileName:string): boolean;
begin
Result:=True;
with TDownLoadURL.Create(nil) do
try
   URL:=sURL;
   Filename:=sLocalFileName;
   try
     ExecuteTarget(nil);
   except
     Result:=False
   end;
finally
   Free;
end;
end;





This function, Download_HTM, downloads a file from the URL specified in the sURL parameter, and saves this file locally under a sLocalFileName name. The function returns True if it succeeds, False otherwise. Of course, this function is to be called from the Button1 OnClick event handler. You can see the code below. Note that, locally, the file is saved as c: emp_adp.newandhot.

procedure TForm1.Button1Click(Sender: TObject);
const
ADPNEWHOTURL=’http://delphi.about.com/cs/newandhot/index.htm’;
TmpFileName=’c: emp_adp.newandhot’;
begin
if NOT Download_HTM(ADPNEWHOTURL,TmpFileName) then
begin
   ShowMessage(‘Error in HTML file download’);
   Exit;
end;

{
more code to be added
}

end;






Note: In the process of downloading a file, the TDownloadURL periodically generates an OnDownloadProgress event, so that you can provide users with feedback about the process. I’ll leave this for you to implement.

String Find Function (StrFnd)

특정 문자열을 찾아내 주는 소스.

델파이 프로그래밍 할 때마다 자주 애용하는 소스이다.
 

function StrFnd( source, key: String): Integer;
var
i, j, flen, slen, klen: Integer;
begin
slen := Length( source);
klen := Length( key);
flen := slen – klen + 1;

for i := 1 to flen do
begin
   if source[i]=key[1] then
   begin
     for j := 2 to klen do
     begin
       if source[i+j-1]<>key[j] then break;
     end;

     if j>klen then
     begin
       // the key is found on the source stream
       Result := i;
       exit;
     end;
   end;
end;

Result := -1;
end;

ActiveX에 다이얼로그 붙이기

ActiveX Control안에 다른 ActiveX Control을 올려놓을때는 차일드 속성외에..
app에 initinstance에서 AfxEnableControlContainer();를 호출해줘야 합니다..
예..
BOOL CClientApp::InitInstance()
{
BOOL bInit = COleControlModule::InitInstance();

if (bInit)
{
// TODO: Add your own module initialization code here.
AfxEnableControlContainer();
}

return bInit;
}
수고하세요.. 직장구하고 있음..^^ 난 초보..^^

[질문 내용]***********************************************
올린이 : 이승민

ActiveX Control에 child 속성의 다이얼로그를 하나 삽입한 후..
이에 관한 클래스를 새로 생성했습니다..
그런후 ActiveX Test Container로 테스트하면 다이얼로그 까지는 나오는데…
그 다이얼로그 위에…다른 ocx를 올려놓은후..
**Ctrl클래스의 OnCreate함수에
다이얼로그의 멤버변수.Create(생성한 다이얼로그 아이디,this);
그리구 같은 클래스의 OnDraw함수에
위저드가 생성한 코드를 지우고,
다이얼로그의 멤버변수.MoveWindow(rcBounds, TRUE);
를 하면..

다이얼로그의 멤버변수.MoveWindow(rcBounds, TRUE);
를 수행하면서 에러가 납니다…

그냥 MFC위저드로해보면 잘 되는데…왜그런건지..- -‘
ocx 내에 또 다른 ocx를 삽입하려면 주의해야할 점이 있나요..
꼭 가르쳐 주세요..

ListCtrl에서 아이템 추가하기 예제

char *strTitle, *strArtist, *strTime;

{
/* Add song information to play list */
LV_ITEM lvitem;

lvitem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_STATE ;
//  lvitem.iImage = MemoryType – 1; /* Set Image Type */
lvitem.state =  0;
lvitem.stateMask = LVIS_DROPHILITED | LVIS_SELECTED | LVIS_FOCUSED;
lvitem.lParam = 0;

int intActualItemNumber;
CString strTemp, strNumber;

if (strArtist[0]!=’

ActiveX에서 바이너리 데이터 파라메터로 안깨지게 받는법

보통 LPCTSTR로 선언해서 쓰는데 그럼 가다가 end of string 이후가 깨져버린다.

그때 파라메터를 CHAR * 로 선언해서 쓰면된다.

Visual C++ 6.0에서는 CHAR* 선언이 불가능하므로 수동으로 고쳐주면된다.


이때 컨트롤 부분에서는 다음과 같은 부분도 수정해주어야 한다.
VTS_BSTR로 선언되어진 부분을 VTS_PI1로 선언해주면된다.

그러면 데이터 송수신시 깨지지 않는다.


from Control


DISP_FUNCTION(CKlientCtrl, “Send”, Send, VT_I2, VTS_BSTR VTS_I2)

EVENT_CUSTOM(“OnReceive”, FireOnReceive, VTS_BSTR  VTS_I4)

to

DISP_FUNCTION(CKlientCtrl, “Send”, Send, VT_I2, VTS_PI1 VTS_I2)

EVENT_CUSTOM(“OnReceive”, FireOnReceive, VTS_PI1 VTS_I4)

모달리스 다이얼로그의 종료 버튼을 클릭했을 때 종료가 안될때…

모달리스 다이얼로그의 종료 버튼을 클릭했을 때 종료가 안될때…


요로코롬 해보슈~



WndProc(..)
{
switch()
{
   case WM_SYSCOMMAND:
   {
     if(wParam==SC_CLOSE)
     {
       EndDialog();//종료
     }
   }
}





void CESTV2WDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else if (nID==SC_CLOSE)
{
   CDialog::OnCancel();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}

DirectShow – NULL Rendering Example

DirectShow를 이용하여 간단히 컨텐츠를 재생하는 프로그램 소스다.

이것만 이해하면 DirectShow의 절반은 이해 한 셈이다.


#include <dshow.h>

#pragma comment(lib, “strmiids.lib”)
// #pragma comment(lib, “quartz.lib”)  // usually not required if not using AMGetErrorText function

void main(void)
{
// Initialize the COM Library
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr))
{
   AfxMessageBox( “ERROR – Could not initialize COM library”);
   return;
}

// Create the filter graph manager and query for interfaces.
IGraphBuilder *pGraph = NULL;
hr = CoCreateInstance( CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **)&pGraph);

if (FAILED(hr))
{
   AfxMessageBox( “ERROR – Could not create the Filter Graph Manager.”);
   return;
}

IMediaControl *pControl = NULL;
IMediaEvent *pEvent = NULL;
hr = pGraph->QueryInterface( IID_IMediaControl, (void **)&pControl);
hr = pGraph->QueryInterface( IID_IMediaEvent, (void **)&pEvent);

// Build the graph.
hr = pGraph->RenderFile( L”D:RESMP3POPPet Shop BoysPet Shop Boys – I wouldn’t normally do this kind of thing.mp3″, NULL);
if (SUCCEEDED(hr))
{
   // Run the graph.
   hr = pControl->Run();
   if (SUCCEEDED(hr))
   {
     // Wait for completion.
     long evCode;
     pEvent->WaitForCompletion( INFINITE, &evCode);

     // Note: Do not use INFINITE in a real application, because it an block indefinitely.
   }
}

pControl->Release();
pEvent->Release();
pGraph->Release();

CoUninitialize();
}

Broadcast를 이용한 Application 종료

가끔 어플리케이션을에게 메시지를 보내서 통채로 죽이고 싶을때가 있다.

어플리케이션들아 우리 같이 종료하자!!!

이럴때는 윈도우 메시지를 정의해놓고,
브로드케스트 해주는 방법을 써주면 좋다.
 

보내는 곳

UINT nCloseRegMsg = ::RegisterWindowMessage(“ISCREEN_CP_APP”);
::PostMessage(HWND_BROADCAST, nCloseRegMsg, 0, 0);


받는 곳
UINT nCloseRegMsg = ::RegisterWindowMessage(“ISCREEN_CP_APP”);
if(pMsg->message == nCloseRegMsg)
{
AfxMessageBox(“I got a MSG<ISCREEN_CP_APP>!”);
}

IE Control을 사용하여 만든 어플리케이션에서 javascript로 어플리케이션에 정의된 함수 호출하는 방법

Embedded XP같은거 사용해서 커스톰 웹브라우져같은거 만들때 이런 방법을 많이 쓴다.
셋톱박스 전용 브라우져 만들때 꼭 써야하는 방식이라고나 할까…


내용 요약:
IE Control을 사용하여 개발하는 어플리케이션 내에 정의된 함수를 javascript로 window.external.[사용자 정의 함수] 로 호출하는 방법.
기본적으로는 함수는 Public으로 정의하여 구현하면 IE위에서 돌아가는 javascipt에서도 Call할수 있다.

# call방법

<script language=javascript>
window.external.사용자정의함수();
</script>


Shows how to customize the Microsoft WebBrowser control in a dialog based app to allow custom context menus, message boxes, windows, modal dialogs and C++ function calls from JavaScript to your application using window.external.

윈도우 옮기는 API – SetWindowPos

 

The SetWindowPos function changes the size, position, and Z order of a child, pop-up, or top-level window. Child, pop-up, and top-level windows are ordered according to their appearance on the screen. The topmost window receives the highest rank and is the first window in the Z order.

BOOL SetWindowPos(
  HWND hWnd,             // handle to window
  HWND hWndInsertAfter,  // placement-order handle
  int X,                 // horizontal position
  int Y,                 // vertical position
  int cx,                // width
  int cy,                // height
  UINT uFlags            // window-positioning flags
);


SAMPLE CODE ========================================

LRESULT CALLBACK WndProc(HWND hWnd,UINT iMessage,WPARAM wParam,LPARAM lParam)
{
        HDC hdc;
        PAINTSTRUCT ps;
        char Mes[]=”왼쪽=위치 변경, 오른쪽=항상 위 옵션 변경”;
        static BOOL bTopMost=FALSE;

        switch(iMessage) {
        case WM_LBUTTONDOWN:
                SetWindowPos(hWnd, HWND_NOTOPMOST,
                        rand()%640, rand()%480, 0, 0, SWP_NOSIZE);
                return 0;
        case WM_RBUTTONDOWN:
                if (bTopMost) {
                        SetWindowPos(hWnd,HWND_NOTOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
                } else {
                        SetWindowPos(hWnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
                }
                bTopMost=~bTopMost;
                return 0;
        case WM_PAINT:
                hdc=BeginPaint(hWnd, &ps);
                TextOut(hdc,10,10,Mes,lstrlen(Mes));
                EndPaint(hWnd, &ps);
                return 0;
        case WM_DESTROY:
                PostQuitMessage(0);
                return 0;
        }
        return(DefWindowProc(hWnd,iMessage,wParam,lParam));
}

CFileDialog – File Open Example

CFileDialog l_SampleDlg(TRUE,NULL,NULL,OFN_OVERWRITEPROMPT,”Text Files (*.txt)|*.txt|Comma Separated Values(*.csv)|*.csv||”);
      int iRet = l_SampleDlg.DoModal();
      CString l_strFileName;
      l_strFileName = l_SampleDlg.GetPathName();

      if(iRet == IDOK)
          MessageBox(l_strFileName);
      else
          MessageBox(“No File Selected!”);

GDI+ Programming 방법

 

[중요1] Graphics 개체를 사용한다.

[중요2] 다음의 헤더선언을 꼭 해야된다

        #include <gdiplus.h>
        using namespace Gdiplus;

        #pragma comment(lib, “gdiplus.lib”) // <- 이부분은 한번반 선언하면 됨. 따라서 stdafx.cpp같은데 두면 좋음

[중요3]         
        ULONG_PTR m_gdiplusToken; // Global로 선언

        // 초기화를 위해 최소 한번 실행
            // 이부분은 GDI 개체, 즉 DC로 만들어지는 개체가 생기기 전에 생성되면 된다.
            // 예를 들어 다이얼로그 선언부 전에 선언하면 좋다.
        Gdiplus::GdiplusStartupInput gdiplusStartupInput;
        Gdiplus::GdiplusStartup( &m_gdiplusToken, &gdiplusStartupInput, NULL);  

                // Exit Instance에 실행
        GdiplusShutdown(m_gdiplusToken);


1. Graphics 개체 만드는 방법

(1) 폼 또는 컨트롤의 Paint 이벤트에서 PaintEventArgs의 일부로서 Graphics 개체에 대한 참조를 받는다.
이 방법은 대개 컨트롤을 그리는 코드를 작성할 때 Graphics 개체에 대한 참조를 가져오는 데 사용된다.

private:
   System::Void Form1_Paint(System::Object *  sender,
      System::Windows::Forms::PaintEventArgs *  pe)
   {
      // Declares the Graphics object and sets it to the Graphics object
      // supplied in the PaintEventArgs.
      Graphics * g = pe->Graphics;
      // Insert code to paint the form here.
   }



(2) 폼 또는 컨트롤의 CreateGraphics 메서드를 호출하여 해당 폼이나 컨트롤의 그리기 화면을 나타내는
Graphics 개체에 대한 참조를 가져온다. 이미 있는 폼이나 컨트롤에서 그리려는 경우에 이 방법을 사용한다.

방법1)

        Graphics * g;
        g = this->CreateGraphics();

방법2)

        // OnPaint() 이벤트에서
        CPaintDC dc(this);
        Graphics g(dc.m_hDC);


(3) Image에서 상속된 개체에서 Graphics 개체를 만든다. (가장 간단)
이 방법은 기존 이미지를 변경하려는 경우에 유용.


        Bitmap * myBitmap = new Bitmap(S”D:Documents and SettingsJoePicsmyPic.bmp”);
        Graphics * g = Graphics::FromImage(myBitmap);


예제)
        ::OnPaint()
        {
                CPaintDC dc(this);
                Graphics g(dc.m_hDC);

                CRect rect;
                GetClientRect( &rect);
                
                Image image(L”image1.jpg”);
                Rect rct( 0, 0, rect.right, rect.bottom);
                g.DrawImage( &image, rct.X, rct.Y, rct.Width, rct.Height);
        }

뭐 어쩌라는 것은 아니고요