블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2735)
Unity3D (815)
Programming (474)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
04-18 00:09

I had a real pain recently where I wanted to control one windows app from another. I found some useful stuff on the net, but nothing that gave an end to end solution. So here’s what I came up with.

Firstly I’ll explain why this is useful. SendMessage is part of the Win32 API, and is used to send messages from one application to another. There are a set of predefined properties that the message can relate to, and these can be used to send messages to existing applications to perform all sorts of useful functions such as changing the font in notepad, or bringing a window to the fore. For more information of the wider use of the SendMessage function, have a look at:

http://www.autohotkey.com/docs/commands/PostMessage.htm

http://msdn.microsoft.com/en-us/library/ms644950(VS.85).aspx

The main use that I’m interested in is passing a specific instruction (via a string) from one app that I’ve written, to another one that I’ve written. This way I can effectively remote control one app from another (particularly useful if you want your main application to open a pop-up, and you don’t want to worry about the pop-up’s performance affecting the main application). Let’s now have a quick look at the SendMessage function:

SendMessage(int hWnd, int Msg, int wParam, int lParam)

hWnd – This is the window instance id of the application you want to send a message to. This id is retrieved using the FindWindow function

Msg – This is the type of message you want to send

wParam – Message specific data you pass in

wParam – Message specific data you pass in

Also used is the FindWindow function. This is to get the relevant window id:

FindWindow(String lpClassName, String lpWindowName)

lpClassName -The name of the class you want

lpWindowName – The name of the window that you want

To send a message that is a string, you need to use the WM_DATACOPY message property. The hard part is that you cannot just send the string as a parameter across. You need to send a pointer to the memory address of the string. If you just want to send an integer as a message you can use the WM_USER message property and send it as a value without a problem.

Below now is a brief listing of my MessageHelper.cs class, for the whole class file see:

http://craigcook.co.uk/samples/MessageHelper.cs.txt

01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Text;
05using System.Runtime.Serialization.Formatters.Binary;
06using System.Runtime.InteropServices;
07using System.Diagnostics;
08 
09public class MessageHelper
10{
11[DllImport("User32.dll")]
12private static extern int RegisterWindowMessage(string lpString);
13 
14[DllImport("User32.dll", EntryPoint = "FindWindow")]
15public static extern Int32 FindWindow(String lpClassName, String lpWindowName);
16 
17//For use with WM_COPYDATA and COPYDATASTRUCT
18[DllImport("User32.dll", EntryPoint = "SendMessage")]
19public static extern int SendMessage(int hWnd, int Msg, int wParam, refCOPYDATASTRUCT lParam);
20 
21//For use with WM_COPYDATA and COPYDATASTRUCT
22[DllImport("User32.dll", EntryPoint = "PostMessage")]
23public static extern int PostMessage(int hWnd, int Msg, int wParam, refCOPYDATASTRUCT lParam);
24 
25[DllImport("User32.dll", EntryPoint = "SendMessage")]
26public static extern int SendMessage(int hWnd, int Msg, int wParam, intlParam);
27 
28[DllImport("User32.dll", EntryPoint = "PostMessage")]
29public static extern int PostMessage(int hWnd, int Msg, int wParam, intlParam);
30 
31[DllImport("User32.dll", EntryPoint = "SetForegroundWindow")]
32public static extern bool SetForegroundWindow(int hWnd);
33 
34public const int WM_USER = 0x400;
35public const int WM_COPYDATA = 0x4A;
36 
37//Used for WM_COPYDATA for string messages
38public struct COPYDATASTRUCT
39{
40     public IntPtr dwData;
41     public int cbData;
42     [MarshalAs(UnmanagedType.LPStr)]
43     public string lpData;
44}
45 
46public bool bringAppToFront(int hWnd)
47{
48     return SetForegroundWindow(hWnd);
49}
50 
51public int sendWindowsStringMessage(int hWnd, int wParam, string msg)
52{
53    int result = 0;
54 
55     if (hWnd != 0)
56     {
57            byte[] sarr = System.Text.Encoding.Default.GetBytes(msg);
58            int len = sarr.Length;
59            COPYDATASTRUCT cds;
60            cds.dwData = (IntPtr)100;
61            cds.lpData = msg;
62            cds.cbData = len + 1;
63            result = SendMessage(hWnd, WM_COPYDATA, wParam, ref cds);
64     }
65 
66     return result;
67}
68 
69public int sendWindowsMessage(int hWnd, int Msg, int wParam, int lParam)
70{
71     int result = 0;
72 
73     if (hWnd != 0)
74     {
75            result = SendMessage(hWnd, Msg, wParam, lParam);
76     }
77 
78     return result;
79}
80 
81public int getWindowId(string className, string windowName)
82{
83 
84     return FindWindow(className, windowName);
85 
86}
87}

So now you can call the code to send a message like so:

MessageHelper msg = new MessageHelper();
int result = 0;
//First param can be null
int hWnd = msg.getWindowId(null, “My App Name”);
result = msg.sendWindowsStringMessage(hWnd, 0, “Some_String_Message”);
//Or for an integer message
result = msg.sendWindowsMessage(hWnd, MessageHelper.WM_USER, 123, 456);

Now all you need to do on the app that you want to receive the message is override the following function in the form class (obviously you can change what the responses are, and you’ll need to create constants for the parameters):

01protected override void WndProc(ref Message m)
02{
03switch (m.Msg)
04{
05     case WM_USER:
06            MessageBox.Show("Message recieved: " + m.WParam + " - " + m.LParam);
07            break;
08     case WM_COPYDATA:
09            COPYDATASTRUCT mystr = new COPYDATASTRUCT();
10            Type mytype = mystr.GetType();
11            mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
12            this.doSomethingWithMessage(mystr.lpData);
13            break;
14}
15base.WndProc(ref m);
16}


출처 : http://boycook.wordpress.com/2008/07/29/c-win32-messaging-with-sendmessage-and-wm_copydata/

반응형
Posted by blueasa
, |