winform与WPF间消息处理

来源:互联网 发布:大气数据系统 编辑:程序博客网 时间:2024/05/21 16:22

当使用winform启动WPF应用时,传参比较简单,直接使用进程之间传递参数,若winform向已启动的WPF中传参数,则使用消息处理

winform程序,本例使用控制台

实体类 

namespace ConsoleApplication1{     [StructLayout(LayoutKind.Sequential)]        public struct Entity        {            public IntPtr dwData;            public int cbData;            [MarshalAs(UnmanagedType.LPStr)]            public string lpData;        } }
</pre><pre name="code" class="csharp">

发送端(控制台程序)

namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            string ch = "";             while (ch.ToLower() != "q")             {                if (!SendMessage("MainWindow",ch))                 {                    Console.WriteLine("无窗口MainWindow");                };                 ch = Console.ReadLine();             }         }         public static bool SendMessage(string windowName, string strMsg)         {             if (strMsg == null) return true;             IntPtr hwnd = (IntPtr)FindWindow(null, windowName   );             if (hwnd != IntPtr.Zero)             {                Entity entity;                entity.dwData = IntPtr.Zero;                entity.lpData = strMsg;                entity.cbData = System.Text.Encoding.Default.GetBytes(strMsg).Length + 1;                 int fromWindowHandler = 0;               //处理为非0,未处理0           int result = SendMessage(hwnd, 0x004A, fromWindowHandler, ref entity);            Console.WriteLine(result);                return true;             }             return false;         }         [DllImport("User32.dll", EntryPoint = "FindWindow")]         private static extern int FindWindow(string lpClassName, string lpWindowName);         [DllImport("User32.dll", EntryPoint = "SendMessage")]         private static extern int SendMessage         (         IntPtr hWnd,         int Msg,         int wParam,         ref Entity lParam         );     }}
接收端(WPF)

namespace WpfApplication29{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow : Window{public MainWindow(){this.InitializeComponent();// 在此点下面插入创建对象所需的代码。}        IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)        {            if (msg == 0x004A)            {                Entity obj = (Entity)System.Runtime.InteropServices.Marshal.PtrToStructure(lParam, typeof(Entity));               if(obj.lpData.Trim()!="")               {                   MessageBox.Show(obj.lpData);
 <span style="white-space:pre"></span>   handled = true;//指示消息是否已处理               }            }            return hwnd;        }        private void WindowLoaded(object sender, RoutedEventArgs e)        {            (PresentationSource.FromVisual(this) as System.Windows.Interop.HwndSource).AddHook(new System.Windows.Interop.HwndSourceHook(WndProc));         } }}



0 0
原创粉丝点击