프로그래밍/API 프로그래밍

두 프로그램간 통신!!

CokeBell 2008. 10. 17. 20:56


// A 프로그램..
#include <windows.h>
#include <stdio.h>

// 두 프로그램간 통신하기 위한 사용자 정의 메세지
#define WM_ADD WM_APP + 100
void main()
{
 HWND hwnd = FindWindow( 0, "B");

 if ( hwnd == 0 )
 {
  printf("B 를 먼저 실행해 주세요\n");
  return ;
 }
 //----------------------------------
 int sum = 0;

 // 블럭킹 함수 , 동기화 함수
// sum = SendMessage(hwnd, WM_ADD, 10, 20 );

 // 비동기 전달.
 BOOL b = PostMessage( hwnd, WM_ADD, 10, 20);

 printf("전송 완료 : %d\n", sum );
}

//////////////////////////////////////////////////////////////////////

//B프로그램

#pragma comment(linker, "/subsystem:windows")

#include <windows.h>

#define WM_ADD  WM_APP + 100

LRESULT CALLBACK WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
 switch( msg )
 { 
 // A 가 보낸 메세지
 case WM_ADD:
  {
   char s[256];
   wsprintf( s, "WM_ADD 도착 : %d, %d", wParam, lParam);

   MessageBox( 0, s, "", MB_OK);

   return wParam + lParam; // SendMessage()의 리턴값이 된다.
  }
      // B를 먼저 실행하고 A를 실행해 보세요.

 case WM_DESTROY:
  PostQuitMessage(0);
  return 0;
 }
 return DefWindowProc( hwnd, msg, wParam, lParam);
}

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
     LPSTR   lpCmdLine, int nShowCmd )
{
 ATOM atom;
 WNDCLASS wc;
 HWND hwnd;
 MSG msg;
 
 wc.cbClsExtra = 0;
 wc.cbWndExtra = 0;
 wc.hbrBackground= (HBRUSH)GetStockObject( WHITE_BRUSH );
 wc.hCursor  = LoadCursor( 0, IDC_ARROW );
 wc.hIcon  = LoadIcon( 0, IDI_APPLICATION);
 wc.hInstance = hInstance;
 wc.lpfnWndProc  = WndProc;
 wc.lpszClassName= "First";
 wc.lpszMenuName = 0;
 wc.style  = 0;

 atom = RegisterClass( &wc);
 
 if ( atom == 0 )
 {
  MessageBox( 0, "Fail To RegisterClass", "Error", MB_OK);
  return 0;
 }

 hwnd = CreateWindowEx( 0, "first", "B", WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, 0, CW_USEDEFAULT,0, 0, 0,
        hInstance, 0);
 ShowWindow( hwnd, nShowCmd);
 UpdateWindow( hwnd );

 while ( GetMessage( &msg, 0, 0, 0) )
 {       
  TranslateMessage(&msg);
  DispatchMessage( &msg);
 }

 return 0;
}