日期:2014-05-18  浏览次数:20641 次

请教一个关于窗体自定义消息(传递消息)的问题(C#语言),请赐教
我先描述一下我的程序,这是一个浏览gif格式图片的查看器,打开gif文件时默认用该查看器查看,当该查看器已经打开的时候,再打开其他的gif格式文件,仍然以原查看器查看,并不是再次打开一个查看器。

起初我是用
public static extern int SendMessage(IntPtr hwnd, uint wMsg, IntPtr wParam, IntPtr lParam);
来传递消息,
我在主窗体中定义了一个方法
LoadImage(string fileName),用于加载目标gif文件,
在program类中定义了一个方法
private static void HandleRunningInstance(Process instance, string[] args)
{
 if (args.Length > 0)
  {
  try
  {
  IntPtr lp = Marshal.StringToCoTaskMemAnsi(args[0] + "\0\0");
  SendMessage(instance.MainWindowHandle, WM_USER + 1, IntPtr.Zero, lp);
  //string fileName = Marshal.PtrToStringAnsi(lp);
  //Log(lp.ToString() + "--" + fileName);
  }
  catch (Exception ex)
  {
  Log(ex.Message);
  }
  }
}

第一个参数是获取的已经打开的查看器的进程,第二个参数是入口Main(string[] args)方法的参数,args里包括目标Gif文件的文件名,
在主窗体中重写了方法:
 protected override void WndProc(ref Message m)
  {
  base.WndProc(ref m);
  if (m.Msg == WM_USER + 1)
  {
  try
  {
  string fileName = Marshal.PtrToStringAnsi(m.LParam);
  Program.Log("WndProc获取到参数:" + fileName.ToString());
  LoadImage(fileName.ToString());
  }
  catch (Exception ex)
  {
  Program.Log("error:" + ex.Message);
  }
  }
  }
可是我用这种方法获取到的fileName是空值。。。


然后传递消息的方法改成了
 public static extern int SendMessage(IntPtr HWnd, uint Msg, int WParam, ref Msg lParam);
对应代码:
private static void HandleRunningInstance(Process instance, string[] args)
  {
  if (args.Length > 0)
  {
  try
  {
  Msg msg = new Msg();
  msg.FileName = args[0];
  SendMessage(instance.MainWindowHandle, WM_USER + 1, 0, ref msg);
  }
  catch (Exception ex)
  {
  Log(ex.Message);
  }
  }
  }


protected override void WndProc(ref Message m)
  {
  base.WndProc(ref m);
  if (m.Msg == WM_USER + 1)
  {
  try
  {
  Msg msg1 = new Msg();
  Program.Log(msg1.GetType().ToString());
  Msg msg = (Msg)m.GetLParam(msg1.GetType());
  string fileName = msg.FileName;
  Program.Log("WndProc获取到参数:" + fileName.ToString());
  LoadImage(fileName.ToString());
  }
  catch (Exception ex)
  {
  Program.Log("error:" + ex.Message);
  }
  }
  }

可是这样又没有取得msg,


我调试得到了LParam参数,可是参数转换成字符串不行,转换成结构也不行,这是怎么回事,请高手指教。

------解决方案--------------------
恭喜!
------解决方案--------------------