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

카테고리

분류 전체보기 (2797)
Unity3D (853)
Programming (479)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (185)
협업 (61)
3DS Max (3)
Game (12)
Utility (68)
Etc (98)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (55)
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

'SendMessage'에 해당되는 글 4건

  1. 2012.05.09 SendMessage C# -> C++ with String
  2. 2012.05.08 C# Win32 messaging with SendMessage and WM_COPYDATA
  3. 2010.12.27 sendmessage in C# 1
  4. 2010.12.26 C# SendMessage Keypress 1

[서론]

  이전에 W.O.W 접속유지 프로그램을 만든적은 있지만 그때는 WOW 캡션이 정해져 있었고, 키입력만으로(방향키를 사용했음) 접속유지가 됐기때문에 단순한 키입력 메시지 전달만 하면 끝이었다. 

  다만.. W.O.W 에서 SendMessage를 먹어버려서 PostMessage로 처리했었다.

  (W.O.W 접속유지 프로그램 링크:http://blueasa.tistory.com/527)


  이번에는 서로(현재는 C# -> C++ 만 되는거 보고 정리함.. 나중에 업뎃 할지도..) SendMessage를 보내서 뭔가 일을 꾸밀(?) 수 있게 해보고 싶은마음에 시작.. 물론 양쪽 프로그램은 내가 직접 만든다는 가정하에..

  세상에 선구자는 많으니 역시나..자료를 찾기 시작.. 이전에 간단하나마 만든 것도 있고..

  말재주는 없으니 본론으로 들어가서 그냥 소스 정리..


[사용된 WinAPI 함수 및 중요 키워드]

FindWindow, SendMessage, WM_COPYDATA


[Send : C#]



[Source]

    public class MessageHelper
    {
        [DllImport("User32.dll")]
        private static extern int RegisterWindowMessage(string lpString);

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        public static extern Int32 FindWindow(String lpClassName, String lpWindowName);

        //For use with WM_COPYDATA and COPYDATASTRUCT
        [DllImport("User32.dll", CharSet = CharSet.Auto, SetLastError = false, EntryPoint = "SendMessage")]
        public static extern int SendMessage(int hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);

        //For use with WM_COPYDATA and COPYDATASTRUCT
        [DllImport("User32.dll", CharSet = CharSet.Auto, SetLastError = false, EntryPoint = "PostMessage")]
        public static extern int PostMessage(int hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);

        //For use with WM_COPYDATA and COPYDATASTRUCT*
        [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
        public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);

        [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "PostMessage")]
        public static extern int PostMessage(int hWnd, int Msg, int wParam, int lParam);

        [DllImport("User32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern bool SetForegroundWindow(int hWnd);

        public const int WM_USER = 0x400;
        public const int WM_SENDER = WM_USER + 4444;
        public const int WM_COPYDATA = 0x4A;

        //Used for WM_COPYDATA for string messages
        //[StructLayout(LayoutKind.Sequential)] 
        public struct COPYDATASTRUCT
        {
            public int dwData;
            public int cbData;
            //[MarshalAs(UnmanagedType.LPStr)]
            public IntPtr lpData;
        }

        public bool BringAppToFront(int hWnd)
        {
            return SetForegroundWindow(hWnd);
        }

        public int SendWindowsStringMessage(int hWnd, int wParam, string command)
        {
            int result = 0;

            if (hWnd != 0)
            {
                byte[] sarr = System.Text.Encoding.Default.GetBytes(command);
                int len = sarr.Length;

                COPYDATASTRUCT cds = new COPYDATASTRUCT();
                //cds.dwData = (IntPtr)100;
                cds.dwData = 0;
                cds.cbData = len + 1;
                //cds.cbData = Marshal.SizeOf(cds);
                cds.lpData = Marshal.StringToHGlobalAnsi(command);
                //cds.lpData = Marshal.StringToCoTaskMemAnsi(command);

                result = SendMessage(hWnd, WM_COPYDATA, wParam, ref cds);
            }

            return result;
        }

        public int SendWindowsMessage(int hWnd, int Msg, int wParam, int lParam)
        {
            int result = 0;

            if (hWnd != 0)
            {
                result = SendMessage(hWnd, Msg, wParam, lParam);
            }

            return result;
        }

        public int GetWindowID(string className, string windowName)
        {
            return FindWindow(className, windowName);
        }
    }





[Use]


int hWnd = messageHelper.GetWindowID(null, windowCaption);
messageHelper.SendWindowsStringMessage(hWnd, 0, String);



[Receive : C++]


[Source]


WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{  
    switch ( msg )   
    {  
    case WM_COPYDATA:  
        {  
            //Used for WM_COPYDATA for string messages  
            struct COPYDATASTRUCT  
            {  
                int dwData;  
                int cbData;  
                PVOID lpData;  
            };  
  
            COPYDATASTRUCT* cp = (COPYDATASTRUCT*)lParam;  
  
            if( NULL != cp )  
            {  
                String strCommand = "";  
                char szCommand[256] = {0,};  
                  
                memcpy( szCommand, cp->lpData, cp->cbData );  
                  
                if(NULL != szCommand)  
                {  
					/// ToDo  
					/// 여기서 받은 문자열로 할 일 하면 됨.  
					/// dwData는 여기선 의미가 없긴한데 enum이나 int 그대로 써서  
					/// switch문 등으로 분기시켜서 여러가지 다양한 처리를 하려고
					/// 처음 소스 짠사람이 만든 것 같다.  
					/// 다른 일도 분류해서 처리하려면 사용하자.  
                }  
            }  
        }  
        break;  
    }  
}  




[주의]

WM_COPYDATA 는 PostMessage로 날릴 수 없다고 한다. SendMessage를 사용하자.

(상대쪽에서 받기 전에 이쪽에서 메모리 해제 되있으면 AV뜨기때문에..)

참고 링크 : http://lunapiece.net/?mid=Tips&listStyle=webzine&document_srl=3780&sort_index=readed_count&order_type=desc


P.s. 마음대로 되지 않고 삽질도 많이해서 여기저기 쓰이지 않는 주석이 남아있긴 하지만.. 삽질기념(?) 그냥 냅두기..

       하도 검색하고 다녀서 참조한 곳을 다 찾기엔 좀 걸리거나 빼먹을 수 도 있을 것 같다. 출처를 찾으러 가야지..



[참조]

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

http://kofmania.tistory.com/45

http://xarfox.tistory.com/45

http://jacking.tistory.com/134

http://www.hoons.kr/board.aspx?Name=qacshap&Mode=2&BoardIdx=10465&Key=&Value=

http://lunapiece.net/?mid=Tips&listStyle=webzine&document_srl=3780&sort_index=readed_count&order_type=desc

- 그 외 못 적은 곳은.. 죄송합니다..;;



반응형
Posted by blueasa
, |

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
, |

sendmessage in C#

Programming/C# / 2010. 12. 27. 01:42
1         [DllImport("user32.dll", SetLastError = true)]  
2         static extern IntPtr FindWindow(string lpClassName, string lpWindowName);  
3  
4         [DllImport("user32.dll", SetLastError = true)]  
5         static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);  
6  
7         [DllImport("user32.dll")]  
8         private static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);  
9  
10         static void Main(string[] args)  
11         {  
12             // Use this to send key strokes  
13             const int WM_KEYDOWN = 0x100;  
14             IntPtr windowHandle = FindWindow("NOTEPAD"null);  
15             IntPtr editHandle = FindWindowEx(windowHandle, IntPtr.Zero, "EDIT"null);  
16             PostMessage(editHandle, WM_KEYDOWN, 'A', 0);  
17             Console.ReadKey();  
18         }

1         [DllImport("user32.dll")]  
2         public static extern int SendMessage(int hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPStr)] string lParam);  
3  
4         [DllImport("user32.dll", SetLastError = true)]  
5         static extern IntPtr FindWindow(string lpClassName, string lpWindowName);  
6  
7         [DllImport("user32.dll", SetLastError = true)]  
8         static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);  
9  
10         static void Main(string[] args)  
11         {  
12             const int WM_SETTEXT = 0x0C;  
13  
14             IntPtr windowHandle = FindWindow("NOTEPAD"null);  
15             IntPtr editHandle = FindWindowEx(windowHandle, IntPtr.Zero, "EDIT"null);  
16             string textToSendToFile = "Input here your text";  
17             SendMessage((int)editHandle, WM_SETTEXT, 0, textToSendToFile);  
18  
19             Console.ReadKey();  
20         }


반응형
Posted by blueasa
, |

C# SendMessage Keypress

Programming/C# / 2010. 12. 26. 23:45
#region Function Imports
 
       
[DllImport("user32.dll")]
       
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
 
       
[DllImport("user32.dll")]
       
static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
 
       
#endregion
 
       
#region Constants
 
       
// Messages
       
const int WM_KEYDOWN = 0x100;
       
const int WM_KEYUP = 0x101;
       
const int WM_CHAR = 0x105;
       
const int WM_SYSKEYDOWN = 0x104;
       
const int WM_SYSKEYUP = 0x105;
 
       
#endregion
 
       
public static void SendKey(string wName, Keys key)
       
{
           
IntPtr hWnd = FindWindow(null, wName);
 
           
SendMessage(hWnd, WM_KEYDOWN, Convert.ToInt32(key), 0);
           
SendMessage(hWnd, WM_KEYUP, Convert.ToInt32(key), 0);
       
}
 
       
public static void SendSysKey(string wName, Keys key)
       
{
           
IntPtr hWnd = FindWindow(null, wName);
 
           
SendMessage(hWnd, WM_SYSKEYDOWN, Convert.ToInt32(key), 0);
           
SendMessage(hWnd, WM_SYSKEYUP, Convert.ToInt32(key), 0);
       
}
 
       
public static void SendChar(string wName, char c)
       
{
           
IntPtr hWnd = FindWindow(null, wName);
 
           
SendMessage(hWnd, WM_CHAR, (int)c, 0);
       
}


반응형
Posted by blueasa
, |