Beispiel #1
0
        protected static void SendReturnData(int communicationNo, IntPtr receiveWindowHandle, object data)
        {
            IntPtr globalData = IntPtr.Zero;

            try
            {
                CopyDataProtocolInfo communicatonData = new CopyDataProtocolInfo(IntPtr.Zero, data);
                byte[] bin = communicatonData.Serialize();
                NativeMethods.COPYDATASTRUCT copyData = new NativeMethods.COPYDATASTRUCT();
                copyData.dwData = IntPtr.Zero;
                copyData.cbData = (uint)bin.Length;
                copyData.lpData = globalData = Marshal.AllocHGlobal(bin.Length);
                Marshal.Copy(bin, 0, copyData.lpData, bin.Length);
                NativeMethods.SendMessage(receiveWindowHandle, NativeMethods.WM_COPYDATA, new IntPtr(communicationNo), ref copyData);
            }
            catch
            {
                //対象アプリケーションプロセスでの実行なので例外は投げない。
            }
            finally
            {
                if (globalData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(globalData);
                }
            }
        }
Beispiel #2
0
 //The window procedure that handles notifications from new application instances
 protected override void WndProc(ref System.Windows.Forms.Message m)
 {
     if (m.Msg == NativeMethods.WM_COPYDATA)
     {
         //convert the message LParam to the WM_COPYDATA structure
         NativeMethods.COPYDATASTRUCT data = (NativeMethods.COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(NativeMethods.COPYDATASTRUCT));
         object obj = null;
         if (data.cbData > 0 && data.lpData != IntPtr.Zero)
         {
             //copy the native byte array to a .net byte array
             byte[] buffer = new byte[data.cbData];
             Marshal.Copy(data.lpData, buffer, 0, buffer.Length);
             //deserialize the buffer to a new object
             obj = deserialize(buffer);
         }
         if (NewInstanceMessage != null)
         {
             NewInstanceMessage.Invoke(this, obj);
         }
     }
     else
     {
         base.WndProc(ref m);
     }
 }
        /// <summary>
        /// 送受信。
        /// </summary>
        /// <param name="targetWindowHandle">送信対象ウィンドウハンドル。</param>
        /// <param name="data">送信データ。</param>
        /// <param name="recieveWindow">受信ウィンドウ。</param>
        /// <returns>受信データ。</returns>
        internal static object SendAndRecieve(IntPtr targetWindowHandle, object data, ReceiveAfterSend recieveWindow)
        {
            //通信番号生成
            int communicationNo = 0;

            if (!recieveWindow.UniqueNoManager.CreateNo(out communicationNo))
            {
                throw new InformationException(ResourcesLocal.Instance.OutOfCommunicationNo);
            }

            //使用可能なスレッドであるかチェック
            if (!recieveWindow.CanUseThread)
            {
                throw new FriendlyOperationException(ResourcesLocal.Instance.ErrorInvalidThreadCall);
            }

            //送受信
            IntPtr globalData = IntPtr.Zero;

            try
            {
                //通信データ作成
                CopyDataProtocolInfo communicationData = new CopyDataProtocolInfo(recieveWindow.Handle, data);

                //シリアライズ
                byte[] bin = communicationData.Serialize();

                //WM_COPYDATAでの送信用構造体に移し替え
                NativeMethods.COPYDATASTRUCT copyData = new NativeMethods.COPYDATASTRUCT();
                copyData.dwData = IntPtr.Zero;
                copyData.cbData = (uint)bin.Length;
                copyData.lpData = globalData = Marshal.AllocHGlobal(bin.Length);
                Marshal.Copy(bin, 0, copyData.lpData, bin.Length);

                //送信
                IntPtr sendRet = NativeMethods.SendMessage(targetWindowHandle, NativeMethods.WM_COPYDATA, new IntPtr(communicationNo), ref copyData);
                if (sendRet != ReceiveForm.SendCopyDataSuccess)
                {
                    throw new FriendlyOperationException(ResourcesLocal.Instance.ErrorAppCommunication);
                }

                //受信データ取得
                object receiveData;
                if (!recieveWindow.GetReceiveData(communicationNo, out receiveData))
                {
                    throw new FriendlyOperationException(ResourcesLocal.Instance.ErrorAppCommunication);
                }
                return(receiveData);
            }
            finally
            {
                //グローバルメモリ解放
                if (globalData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(globalData);
                }
                recieveWindow.UniqueNoManager.FreeNo(communicationNo);
            }
        }
Beispiel #4
0
        public static void SendData(string windowName, byte[] data)
        {
            // Find the main window of the other instance.

            var handle = IntPtr.Zero;

            for (int i = 0; i < 3; i++)
            {
                handle = NativeMethods.FindWindow(null, windowName);

                if (handle != IntPtr.Zero)
                {
                    break;
                }

                // Application may still be starting.

                Thread.Sleep(320);
            }

            if (handle == IntPtr.Zero)
            {
                return;
            }

            // Allow set foreground window.

            uint processId;

            NativeMethods.GetWindowThreadProcessId(handle, out processId);

            NativeMethods.AllowSetForegroundWindow(processId);

            // Send the arguments.

            var payload = NativeMethods.LocalAlloc(0x40, (UIntPtr)data.Length);

            try
            {
                NativeMethods.COPYDATASTRUCT copyData = new NativeMethods.COPYDATASTRUCT();

                copyData.dwData = (IntPtr)1;
                copyData.lpData = payload;
                copyData.cbData = data.Length;

                Marshal.Copy(data, 0, copyData.lpData, data.Length);

                NativeMethods.SendMessage(handle, NativeMethods.WM_COPYDATA, IntPtr.Zero, ref copyData);
            }
            finally
            {
                NativeMethods.LocalFree(payload);
            }
        }
Beispiel #5
0
        private void SendArgs(string args)
        {
            Logger.Info($"UCR is already running, sending args: {{{args}}}");
            // Find the window with the name of the main form
            var processes = GetProcesses();

            processes = processes.Where(p => p.Id != Process.GetCurrentProcess().Id).ToArray();
            if (processes.Length == 0)
            {
                return;
            }

            IntPtr ptrCopyData = IntPtr.Zero;

            try
            {
                // Create the data structure and fill with data
                NativeMethods.COPYDATASTRUCT copyData = new NativeMethods.COPYDATASTRUCT
                {
                    dwData = new IntPtr(2),
                    cbData = args.Length + 1,
                    lpData = Marshal.StringToHGlobalAnsi(args)
                };
                // Just a number to identify the data type
                // One extra byte for the \0 character

                // Allocate memory for the data and copy
                ptrCopyData = Marshal.AllocCoTaskMem(Marshal.SizeOf(copyData));
                Marshal.StructureToPtr(copyData, ptrCopyData, false);

                // Send the message
                foreach (var proc in processes)
                {
                    if (proc.MainWindowHandle == IntPtr.Zero)
                    {
                        continue;
                    }
                    NativeMethods.SendMessage(proc.MainWindowHandle, NativeMethods.WM_COPYDATA, IntPtr.Zero, ptrCopyData);
                }
            }
            catch (Exception e)
            {
                Logger.Error("Unable to send args to existing process", e);
            }
            finally
            {
                // Free the allocated memory after the control has been returned
                if (ptrCopyData != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(ptrCopyData);
                }
            }
        }
Beispiel #6
0
        public bool Active(string data)
        {
            var    processId         = Process.GetCurrentProcess().Id;
            string targetProcessName = Constants.ProcessName; // 프로세스 이름

            var process = Process.GetProcesses()
                          .Where(p => p.ProcessName == targetProcessName && p.Id != processId)
                          .FirstOrDefault();

            if (process != null)
            {
                process.WaitForInputIdle(100);
                process.Refresh();

                //! 메인 윈도우가 숨겨지면 핸들을 찾을 수 없습니다.
                // AppBrowser를 Clickonce 게시 메인 프로젝트로 옮겨야 하는 원인입니다.
                IntPtr ptrWnd      = process.MainWindowHandle;
                IntPtr ptrCopyData = IntPtr.Zero;

                try
                {
                    // Create the data structure and fill with data
                    NativeMethods.COPYDATASTRUCT copyData = new NativeMethods.COPYDATASTRUCT();
                    copyData.dwData = new IntPtr(2);    // Just a number to identify the data type
                    copyData.cbData = data.Length + 1;  // One extra byte for the \0 character
                    copyData.lpData = Marshal.StringToHGlobalAnsi(data);

                    // Allocate memory for the data and copy
                    ptrCopyData = Marshal.AllocCoTaskMem(Marshal.SizeOf(copyData));
                    Marshal.StructureToPtr(copyData, ptrCopyData, false);

                    // Send the message 메시지를 전송합니다.
                    NativeMethods.SendMessage(ptrWnd, NativeMethods.WM_COPYDATA, IntPtr.Zero, ptrCopyData);
                }
                catch (Exception ex)
                {
                    throw;
                }
                finally
                {
                    // Free the allocated memory after the contol has been returned
                    if (ptrCopyData != IntPtr.Zero)
                    {
                        Marshal.FreeCoTaskMem(ptrCopyData);
                    }
                }

                return(true);
            }

            return(false);
        }
        //send a notification to the already existing instance that a new instance was started
        private bool NotifyPreviousInstance(object message)
        {
            //First, find the window of the previous instance
            IntPtr handle = NativeMethods.FindWindow(null, _id);

            if (handle != IntPtr.Zero)
            {
                //create a GCHandle to hold the serialized object.
                GCHandle bufferHandle = new GCHandle();
                try
                {
                    byte[] buffer;
                    NativeMethods.COPYDATASTRUCT data = new NativeMethods.COPYDATASTRUCT();
                    if (message != null)
                    {
                        //serialize the object into a byte array
                        buffer = Serialize(message);
                        //pin the byte array in memory
                        bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);

                        data.dwData = 0;
                        data.cbData = buffer.Length;
                        //get the address of the pinned buffer
                        data.lpData = bufferHandle.AddrOfPinnedObject();
                    }

                    GCHandle dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
                    try
                    {
                        NativeMethods.SendMessage(handle, NativeMethods.WM_COPYDATA, IntPtr.Zero, dataHandle.AddrOfPinnedObject());
                        NativeMethods.SetForegroundWindow(handle); // Give focus to first instance
                        return(true);
                    }
                    finally
                    {
                        dataHandle.Free();
                    }
                }
                finally
                {
                    if (bufferHandle.IsAllocated)
                    {
                        bufferHandle.Free();
                    }
                }
            }
            return(false);
        }
Beispiel #8
0
 IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
 {
     if (msg == NativeMethods.WM_COPYDATA)
     {
         // Extract the file name
         NativeMethods.COPYDATASTRUCT copyData = (NativeMethods.COPYDATASTRUCT)Marshal.PtrToStructure(lParam, typeof(NativeMethods.COPYDATASTRUCT));
         int dataType = (int)copyData.dwData;
         if (dataType == 2)
         {
             string message = Marshal.PtrToStringAnsi(copyData.lpData);
             MessageReceived?.Invoke(message);
         }
     }
     handled = true;
     return(IntPtr.Zero);
 }
Beispiel #9
0
        public static void SendDataMessage(Process targetProcess, string msg)
        {
            //Copy the string message to a global memory area in unicode format
            IntPtr _stringMessageBuffer = Marshal.StringToHGlobalUni(msg);

            //Prepare copy data structure
            NativeMethods.COPYDATASTRUCT _copyData = new NativeMethods.COPYDATASTRUCT();
            _copyData.dwData = IntPtr.Zero;
            _copyData.lpData = _stringMessageBuffer;
            _copyData.cbData = msg.Length * 2;//Number of bytes required for marshalling this string as a series of unicode characters
            IntPtr _copyDataBuff = IntPtrAlloc(_copyData);

            //Send message to the other process
            SendMessage(targetProcess.MainWindowHandle, WM_COPYDATA, IntPtr.Zero, _copyDataBuff);

            Marshal.FreeHGlobal(_copyDataBuff);
            Marshal.FreeHGlobal(_stringMessageBuffer);
        }
 protected override void WndProc(ref Message m)
 {
     if (m.Msg == NativeMethods.WM_COPYDATA)
     {
         NativeMethods.COPYDATASTRUCT data = (NativeMethods.COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(NativeMethods.COPYDATASTRUCT));
         object obj = null;
         if (data.cbData > 0 && data.lpData != IntPtr.Zero)
         {
             byte[] buffer = new byte[data.cbData];
             Marshal.Copy(data.lpData, buffer, 0, buffer.Length);
             obj = Deserialize(buffer);
         }
         _theInstance.OnNewInstanceMessage(obj);
     }
     else
     {
         base.WndProc(ref m);
     }
 }
Beispiel #11
0
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == NativeMethods.WM_SHOWBIVROSTPLAYER)
            {
                BringToFront();
                handled = true;
            }
            if (msg == NativeMethods.WM_COPYDATA)
            {
                NativeMethods.COPYDATASTRUCT cps = (NativeMethods.COPYDATASTRUCT)System.Runtime.InteropServices.Marshal.PtrToStructure(lParam, typeof(NativeMethods.COPYDATASTRUCT));
                string data = cps.lpData;

                BringToFront(data);
                handled = true;
            }

            InputDevices.NavigatorInputDevice.WndProc(msg, wParam, lParam);

            return(IntPtr.Zero);
        }
        private bool NotifyPreviousInstance(object message)
        {
            IntPtr handle = NativeMethods.FindWindow(null, _id);

            if (handle != IntPtr.Zero)
            {
                GCHandle bufferHandle = new GCHandle();
                try
                {
                    NativeMethods.COPYDATASTRUCT data = new NativeMethods.COPYDATASTRUCT();
                    if (message != null)
                    {
                        byte[] buffer = Serialize(message);
                        bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);

                        data.dwData = 0;
                        data.cbData = buffer.Length;
                        data.lpData = bufferHandle.AddrOfPinnedObject();
                    }

                    GCHandle dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
                    try
                    {
                        NativeMethods.SendMessage(handle, NativeMethods.WM_COPYDATA, IntPtr.Zero, dataHandle.AddrOfPinnedObject());
                        return(true);
                    }
                    finally
                    {
                        dataHandle.Free();
                    }
                }
                finally
                {
                    if (bufferHandle.IsAllocated)
                    {
                        bufferHandle.Free();
                    }
                }
            }
            return(false);
        }
Beispiel #13
0
        protected override void WndProc(ref Message message)
        {
            if (message.Msg == NativeMethods.WM_COPYDATA)
            {
                NativeMethods.COPYDATASTRUCT copyData = (NativeMethods.COPYDATASTRUCT)Marshal.PtrToStructure(message.LParam, typeof(NativeMethods.COPYDATASTRUCT));
                int dataType = (int)copyData.dwData;
                if (dataType == 2)
                {
                    string   msgContent = Marshal.PtrToStringAnsi(copyData.lpData);
                    string   action     = msgContent.Extract("<", ">")[0];
                    string[] data       = msgContent.Extract("</", "/>");
                    switch (action)
                    {
                    case RouteMessageContants.DOWNLOAD:
                        DownloadTask(data[0]);
                        break;

                    case RouteMessageContants.FILE_SHARE_URL:
                        FileShareUrlTask(data[0]);
                        break;

                    case RouteMessageContants.LOGOUT:
                        Application.Exit();
                        break;

                    default:
                        throw new Exception($"{action} action is not valid");
                    }
                }
                else
                {
                    throw new Exception(string.Format("Unrecognized data type = {0}.", dataType));
                }
            }
            else
            {
                base.WndProc(ref message);
            }
        }
Beispiel #14
0
 private static bool ProcessCopyData(ref Message message, out CopyDataProtocolInfo data)
 {
     data = null;
     if (message.Msg == NativeMethods.WM_COPYDATA)
     {
         //デシリアライズ
         //これが失敗するということは通信の状態が正常ではないので、詳細は返さず、ただ、通信に失敗したことだけ通知する
         try
         {
             NativeMethods.COPYDATASTRUCT globalData = (NativeMethods.COPYDATASTRUCT)message.GetLParam(typeof(NativeMethods.COPYDATASTRUCT));
             byte[] bin = new byte[(int)globalData.cbData];
             Marshal.Copy(globalData.lpData, bin, 0, bin.Length);
             data           = CopyDataProtocolInfo.Deserialize(bin);
             message.Result = SendCopyDataSuccess;
         }
         catch
         {
             message.Result = IntPtr.Zero;
         }
         return(true);
     }
     return(false);
 }
Beispiel #15
0
        protected override void WndProc(ref Message m)
        {
            // 전송된 메시지를 처리합니다.
            if (m.Msg == NativeMethods.WM_COPYDATA)
            {
                // Extract the file name
                NativeMethods.COPYDATASTRUCT copyData = (NativeMethods.COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(NativeMethods.COPYDATASTRUCT));
                int dataType = (int)copyData.dwData;
                if (dataType == 2)
                {
                    string data = Marshal.PtrToStringAnsi(copyData.lpData);

                    SendMessage(data);
                }
                else
                {
                    MessageBox.Show(String.Format("Unrecognized data type = {0}.", dataType), "SendMessageDemo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                base.WndProc(ref m);
            }
        }
        public static bool SendData(string data)
        {
            var handle = NativeMethods.FindWindow(null, Id);

            if (handle == IntPtr.Zero)
            {
                return(false);
            }

            var buffer   = Marshal.StringToHGlobalUni(data ?? "");
            var copyData = new NativeMethods.COPYDATASTRUCT();

            copyData.dwData = IntPtr.Zero;
            copyData.lpData = buffer;
            copyData.cbData = data?.Length * 2 ?? 0;
            var copyDataBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(copyData));

            Marshal.StructureToPtr(copyData, copyDataBuffer, false);
            NativeMethods.SendMessage(handle, NativeMethods.WM_COPYDATA, IntPtr.Zero, copyDataBuffer);
            Marshal.FreeHGlobal(copyDataBuffer);
            Marshal.FreeHGlobal(buffer);

            return(true);
        }
Beispiel #17
0
        protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
        {
            Application.ShutdownMode = ShutdownMode.OnMainWindowClose;
            //AddPathPatch();

            logger = new Logger("bootstrap");

            Application.Current.DispatcherUnhandledException += (_s, _e) => logger.Fatal(_e.Exception, "unhandled application exception");
            AppDomain.CurrentDomain.UnhandledException       += (_s, _e) => logger.Fatal(_e.ExceptionObject as Exception, "unhandled application domain exception");


            LoggerManager.RegisterListener(new TraceLogListener(false));

            //LoggerManager.RegisterListener(new WindowsEventLogListener());


            System.Windows.Forms.Application.EnableVisualStyles();

            if (!System.Diagnostics.Debugger.IsAttached && ApplicationDeployment.IsNetworkDeployed)
            {
                //logger.Info("Copying appref and associating icons and file extensions");
                Logic.Prepare(ApplicationDeployment.CurrentDeployment.DataDirectory + Path.DirectorySeparatorChar);

                Task.Factory.StartNew(() =>
                {
                    CopyApplicationReference();
                    SetAddRemoveProgramsIcon();
                    AssociateFileExtensions("rundll32.exe dfshim.dll,ShOpenVerbShortcut " + Logic.LocalDataDirectory + "Bivrost360Player.appref-ms" + "|%1");
                });
            }
            else
            {
                //logger.Info("Not copying appref and associating icons and file extensions - but making a stub, because this app is not network deployed");
                {
                    // Check for application identity (UWP)
                    string path;
                    try
                    {
                        path = Windows.Storage.ApplicationData.Current.LocalFolder.Path + Path.DirectorySeparatorChar;
                    }
                    catch (InvalidOperationException)
                    {
                        // If no application identity, use application path (desktop/clickonce app)
                        path = (Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase) + Path.DirectorySeparatorChar).Remove(0, "file:\\".Length);
                    }
                    Logic.Prepare(path);

                    //MessageBox.Show(Windows.Storage.ApplicationData.Current.LocalFolder.Path);
                    string runArgument = "360player.exe |%1";
                    foreach (var ext in MediaDecoder.SupportedFileExtensions)
                    {
                        AssociateExtension($".{ext}", runArgument);
                    }
                }
            }

            LoggerManager.RegisterListener(new TextFileLogListener(Logic.LocalDataDirectory));
            logger.Info("Registered all listeners");



            string[] args = Environment.GetCommandLineArgs();
            if (args.Length > 0)
            {
                logger.Info("Received command line arguments: " + string.Join(", ", args));
            }

            try
            {
                if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments != null)
                {
                    args = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData;
                    logger.Info("Forwarding activation arguments as command line: " + string.Join(", ", args));
                }
            } catch (Exception ex)
            {
                //MessageBox.Show("ex: " + ex.Message + "\n" + ex.StackTrace);
            }



            try
            {
                mutex.WaitOne(TimeSpan.Zero, true);
            }
            catch (AbandonedMutexException exc)
            {
                mutex.ReleaseMutex();
            }

            if (mutex.WaitOne(TimeSpan.Zero, true) || System.Diagnostics.Debugger.IsAttached)
            {
                logger.Info("Initiating player window...");
                ownMutex = true;

                if (args != null && args.Length > 0)
                {
                    var lastArgument = args[args.Length - 1];
                    if (!lastArgument.ToLowerInvariant().EndsWith(".exe") && !lastArgument.ToLowerInvariant().EndsWith(".application"))
                    {
                        logger.Info("Forwarding argument from command line:");
                        ShellViewModel.FileFromArgs = lastArgument;
                    }
                }

                DisplayRootViewFor <ShellViewModel>();
            }
            else
            {
                logger.Info("This is a secondary instance - forwarding the file that should be played (if any) to the main instance.");
                if (args.Length > 0)
                {
                    if (!string.IsNullOrWhiteSpace(args[args.Length - 1]))
                    {
                        string str = args[args.Length - 1];

                        if (!str.ToLowerInvariant().EndsWith(".exe") && !str.ToLowerInvariant().EndsWith(".application"))
                        {
                            var cds = new NativeMethods.COPYDATASTRUCT
                            {
                                dwData = new IntPtr(3),
                                cbData = str.Length + 1,
                                lpData = str
                            };

                            //MessageBox.Show("Sending: " + cds.lpData);

                            IntPtr bwin = GetPlayerWindow();
                            logger.Info("Sending to player window: " + bwin.ToString());
                            NativeMethods.SendMessage(bwin, NativeMethods.WM_COPYDATA, IntPtr.Zero, ref cds);


                            //Clipboard.SetText(args[1]);
                            //NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWBIVROSTPLAYER, IntPtr.Zero, IntPtr.Zero);

                            //string str = args[0];
                            //var cds = new NativeMethods.COPYDATASTRUCT
                            //{
                            //	dwData = new IntPtr(3),
                            //	cbData = str.Length + 1,
                            //	lpData = str
                            //};
                            //IntPtr bwin = NativeMethods.FindWindow(null, "Bivrost 360Player");
                            //NativeMethods.SendMessage(bwin, NativeMethods.WM_COPYDATA, IntPtr.Zero, ref cds);
                        }
                    }
                }

                //	else if(args.Length == 3)
                //{
                //	if (!string.IsNullOrWhiteSpace(args[1]) && !string.IsNullOrWhiteSpace(args[2]))
                //	{
                //		if (args[1] == "--bivrost-protocol")
                //		{
                //			Clipboard.SetText(args[2]);
                //			NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWBIVROSTPLAYER, IntPtr.Zero, IntPtr.Zero);
                //		}
                //	}
                //}
                Application.Shutdown();
            }
        }
Beispiel #18
0
        public static void SendData(string windowName, byte[] data)
        {
            // Find the main window of the other instance.

            var handle = IntPtr.Zero;

            for (int i = 0; i < 3; i++)
            {
                handle = NativeMethods.FindWindow(null, windowName);

                if (handle != IntPtr.Zero)
                    break;

                // Application may still be starting.

                Thread.Sleep(320);
            }

            if (handle == IntPtr.Zero)
                return;

            // Allow set foreground window.

            uint processId;

            NativeMethods.GetWindowThreadProcessId(handle, out processId);

            NativeMethods.AllowSetForegroundWindow(processId);

            // Send the arguments.

            var payload = NativeMethods.LocalAlloc(0x40, (UIntPtr)data.Length);

            try
            {
                NativeMethods.COPYDATASTRUCT copyData = new NativeMethods.COPYDATASTRUCT();

                copyData.dwData = (IntPtr)1;
                copyData.lpData = payload;
                copyData.cbData = data.Length;

                Marshal.Copy(data, 0, copyData.lpData, data.Length);

                NativeMethods.SendMessage(handle, NativeMethods.WM_COPYDATA, IntPtr.Zero, ref copyData);
            }
            finally
            {
                NativeMethods.LocalFree(payload);
            }
        }
Beispiel #19
0
    static void Main(string[] args)
    {
        bool isNewInstance;

        using (Mutex singleMutex = new Mutex(true, "3549b015-0564-4e97-b519-2a911a927b45", out isNewInstance))
        {
            string        currentDirectory   = Directory.GetCurrentDirectory();
            List <string> files              = new List <string>();
            bool          hasUnsupportedArgs = false;
            List <string> supportedArgs      = new List <string>();
            foreach (string arg in args)
            {
                if (!arg.StartsWith("-"))
                {
                    string fullFilePath = Path.Combine(currentDirectory, arg);
                    files.Add(fullFilePath);
                }
                else if (arg.StartsWith("-line="))
                {
                    supportedArgs.Add(arg);
                }
                else if (arg.StartsWith("-column="))
                {
                    supportedArgs.Add(arg);
                }
                else
                {
                    hasUnsupportedArgs = true;
                }
            }
            if (hasUnsupportedArgs)
            {
                files.Clear();
            }
            if (isNewInstance || files.Count == 0)
            {
                // Start the form with the file name as a parameter
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm(args));
            }
            else
            {
                Process current = Process.GetCurrentProcess();
                foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                {
                    if (process.Id != current.Id)
                    {
                        IntPtr ptrWnd = process.MainWindowHandle;
                        SetForegroundWindow(ptrWnd);
                        IntPtr ptrCopyData = IntPtr.Zero;
                        try
                        {
                            string text = string.Join("+", files.ToArray()) + "++" + string.Join("+", supportedArgs.ToArray());
                            // Create the data structure and fill with data
                            NativeMethods.COPYDATASTRUCT copyData = new NativeMethods.COPYDATASTRUCT();
                            copyData.dwData = new IntPtr(2);    // Just a number to identify the data type
                            copyData.cbData = text.Length + 1;  // One extra byte for the \0 character
                            copyData.lpData = Marshal.StringToHGlobalAnsi(text);

                            // Allocate memory for the data and copy
                            ptrCopyData = Marshal.AllocCoTaskMem(Marshal.SizeOf(copyData));
                            Marshal.StructureToPtr(copyData, ptrCopyData, false);

                            // Send the message
                            NativeMethods.SendMessage(ptrWnd, NativeMethods.WM_COPYDATA, IntPtr.Zero, ptrCopyData);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString(), "Typewriter.NET", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        finally
                        {
                            // Free the allocated memory after the contol has been returned
                            if (ptrCopyData != IntPtr.Zero)
                            {
                                Marshal.FreeCoTaskMem(ptrCopyData);
                            }
                        }
                        break;
                    }
                }
            }
        }
    }
		/// <summary>
		/// Sends a string to a window handle via WM_COPYDATA.
		/// </summary>
		/// <param name="args">The command line arguments to send.</param>
		/// <param name="hwnd">The window handle to send to.</param>
		private void SendData(string[] args, IntPtr hwnd)
		{
			if (hwnd == IntPtr.Zero) return;

			var data = args != null && args.Length > 0 ? CommandLine.Pack(args) : string.Empty;

			using (var cds = new NativeMethods.COPYDATASTRUCT
			{
				dwData = CopyDataIdentifier,
				cbData = (data.Length + 1)*2, // Unicode string length + terminating zero.
				lpData = Marshal.StringToHGlobalUni(data)
			})
			{
				var hcds = Marshal.AllocHGlobal(Marshal.SizeOf(cds));
				try
				{
					Marshal.StructureToPtr(cds, hcds, true);
					UnsafeNativeMethods.SendMessage(new HandleRef(this, hwnd), NativeMethods.WM_COPYDATA, IntPtr.Zero, hcds);
				}
				finally
				{
					Marshal.FreeHGlobal(hcds);
				}
			}
		}
Beispiel #21
0
        public IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam)
        {
            switch ((NativeMethods.WM)msg)
            {
            case NativeMethods.WM.COPYDATA:
                if (lParam == IntPtr.Zero)
                {
                    CairoLogger.Instance.Debug("TrayService: CopyData is null");
                    break;
                }

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

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

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

                        if (AppBarMessageAction(amd))
                        {
                            return((IntPtr)1);
                        }
                    }
                    else
                    {
                        CairoLogger.Instance.Debug("TrayService: AppBar message received, but with unknown size");
                    }
                    break;

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

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

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

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

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

                break;

            case NativeMethods.WM.WINDOWPOSCHANGED:
                NativeMethods.WINDOWPOS wpos = (NativeMethods.WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(NativeMethods.WINDOWPOS));

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

                    CairoLogger.Instance.Debug("TrayService: Shell_TrayWnd became visible; hiding");
                }
                break;
            }

            if (msg == (int)NativeMethods.WM.COPYDATA || msg == (int)NativeMethods.WM.ACTIVATEAPP)
            {
                IntPtr fwdResult = IntPtr.Zero;

                NativeMethods.EnumWindows((enumHwnd, enumLParam) =>
                {
                    if (enumHwnd != HwndTray && enumHwnd != hWnd)
                    {
                        StringBuilder className = new StringBuilder(256);
                        NativeMethods.GetClassName(enumHwnd, className, 256);

                        if (className.ToString() == "Shell_TrayWnd")
                        {
                            fwdResult = NativeMethods.SendMessage(enumHwnd, msg, wParam, lParam);
                        }
                    }

                    return(true);
                }, 0);

                return(fwdResult);
            }

            return(NativeMethods.DefWindowProc(hWnd, msg, wParam, lParam));
        }
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Get the filename if it exists
            string fileName = "test 2";
            if (args.Length == 1)
                fileName = args[0];

            // If a mutex with the name below already exists,
            // one instance of the application is already running
            bool isNewInstance;
            Mutex singleMutex = new Mutex(true, "MyAppMutex", out isNewInstance);
            if (isNewInstance)
            {
                // Start the form with the file name as a parameter
                Form1 frm = new Form1(fileName);
                Application.Run(frm);
            }
            else
            {
                string windowTitle = "SystemTrayApp";
                windowTitle = "SendMessage Demo";
                // Find the window with the name of the main form
                IntPtr ptrWnd = NativeMethods.FindWindow(null, windowTitle);
                if (ptrWnd == IntPtr.Zero)
                {
                    MessageBox.Show(String.Format("No window found with the title '{0}'.", windowTitle), "Program", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    IntPtr ptrCopyData = IntPtr.Zero;
                    try
                    {
                        // Create the data structure and fill with data
                        NativeMethods.COPYDATASTRUCT copyData = new NativeMethods.COPYDATASTRUCT();
                        copyData.dwData = new IntPtr(2);    // Just a number to identify the data type
                        copyData.cbData = fileName.Length + 1;  // One extra byte for the \0 character
                        copyData.lpData = Marshal.StringToHGlobalAnsi(fileName);

                        // Allocate memory for the data and copy
                        ptrCopyData = Marshal.AllocCoTaskMem(Marshal.SizeOf(copyData));
                        Marshal.StructureToPtr(copyData, ptrCopyData, false);

                        // Send the message
                        NativeMethods.SendMessage(ptrWnd, NativeMethods.WM_COPYDATA, IntPtr.Zero, ptrCopyData);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), "SendMessage Demo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        // Free the allocated memory after the contol has been returned
                        if (ptrCopyData != IntPtr.Zero)
                            Marshal.FreeCoTaskMem(ptrCopyData);
                        singleMutex.ReleaseMutex();
                    }
                }
            }
        }