操作系统 实验八
自定义消息实现进程间通信
Windows应用程序接收到控制台应用程序发送的设置窗口标题信息后,将窗口标题设置为控制台应用程序的设置值。
#include<windows.h>
static const char m_szName[]="窗口";
//这是输入窗口
LRESULT CALLBACK WindowProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
static DWORD tid=0;
static char chInput=0;
HDC hDC;
PAINTSTRUCT ps;
switch(uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_USER:
tid=wParam;
SetWindowText(hWnd,"收到");
break;
case WM_CHAR:
if(tid)
{
switch(wParam)
{
case '1':
chInput='1';
PostThreadMessage(tid,WM_USER+1,0,0);
InvalidateRect(hWnd,NULL,TRUE);
break;
case '2':
chInput='2';
PostThreadMessage(tid,WM_USER+2,0,0);
InvalidateRect(hWnd,NULL,TRUE);
break;
}
}
case WM_PAINT:
hDC=BeginPaint(hWnd,&ps);
if(chInput=='1')
{
TextOut(hDC,15,15,"请在此窗口输入1或2",18);
TextOut(hDC,25,55,"用户输入1",9);
chInput='0';
}
else
if(chInput=='2')
{
TextOut(hDC,15,15,"请在此窗口输入1或2",18);
TextOut(hDC,25,55,"用户输入2",9);
chInput='0';
}
else
{
TextOut(hDC,15,15,"请在此窗口输入1或2",18);
TextOut(hDC,25,55,"用户未输入",10);
}
EndPaint(hWnd,&ps);
break;
case WM_GETTEXT:
return DefWindowProc(hWnd,uMsg,wParam,lParam);
case WM_SETTEXT:
return DefWindowProc(hWnd,uMsg,wParam,lParam);
default:
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
return 0;
}
int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPreInstance, LPSTR lpCmdLine,int nCmdShow)
{
HWND hWnd;
WNDCLASS wc;
MSG sMsg;
int ret;
memset(&wc,0,sizeof(WNDCLASS));
wc.style=CS_VREDRAW|CS_HREDRAW;
wc.lpfnWndProc=(WNDPROC)WindowProc;
wc.hCursor=LoadCursor(NULL,IDC_ARROW);
wc.hbrBackground=(HBRUSH)(COLOR_WINDOW);
wc.lpszClassName=m_szName;
RegisterClass(&wc);
hWnd=CreateWindow(m_szName,m_szName,WS_OVERLAPPEDWINDOW,100,100,320,240,NULL,NULL,hInstance,NULL);
ShowWindow(hWnd,nCmdShow);
while(ret=GetMessage(&sMsg,NULL,0,0))
if(ret!=-1)
{
TranslateMessage(&sMsg);
DispatchMessage(&sMsg);
}
return 0;
}
#include<windows.h>
#include<stdio.h>
static HWND m_hWnd=0;
//这是响应窗口
void process_msg(UINT msg,WPARAM wp,LPARAM lp)
{
char buf[100];
static int i=1;
if(!m_hWnd) return;
switch(msg)
{
case WM_USER+1:
SendMessage(m_hWnd,WM_GETTEXT,sizeof(buf),(LPARAM)buf);
printf("你现在叫:%s\n\n",buf);
break;
case WM_USER+2:
sprintf(buf,"我是窗口%d",i++);
SendMessage(m_hWnd,WM_SETTEXT,sizeof(buf),(LPARAM)buf);
printf("给你改名\n\n");
break;
}
}
int main()
{
MSG sMsg;
int ret;
printf("",GetCurrentThreadId());
m_hWnd=FindWindow(NULL,"窗口");
if(m_hWnd)
{
printf("找到窗口%x\n\n",m_hWnd);
SendMessage(m_hWnd,WM_USER,GetCurrentThreadId(),0);
}
else
printf("没有找到窗口\n\n");
while(ret=GetMessage(&sMsg,(HWND)NULL,(WPARAM)0,(LPARAM)0))
if(ret!=-1)
process_msg(sMsg.message,sMsg.wParam,sMsg.lParam);
return 0;
}