SendMessage API で WM_COPYDATA を使用した例です。
A側 ( Windowsフォームアプリケーション・プロジェクトのプロパティの「ビルド」の「アンセーフコードの許可」にチェックを入れる必要あり )
using System;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
[StructLayout(LayoutKind.Sequential)]
private struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}
private const int WM_COPYDATA = 0x004A;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Process.Start(@"C:\...\ConsoleApplication1.exe ", this.Handle.ToString());
}
unsafe protected override void WndProc(ref Message m)
{
if( m.Msg == WM_COPYDATA ) {
COPYDATASTRUCT *pcds = (COPYDATASTRUCT*)m.LParam.ToPointer();
if( pcds->cbData == 0 ) {
MessageBox.Show("正常に起動しました。",this.Text, MessageBoxButtons.OK,MessageBoxIcon.Information);
} else {
MessageBox.Show("エラーです。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
m.Result = new IntPtr(-1);
this.Close();
}
base.WndProc(ref m);
}
}
}
B側 ( コンソールアプリケーション )
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(int hWnd, UInt32 Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
private const int WM_COPYDATA = 0x004A;
[StructLayout(LayoutKind.Sequential)]
private struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}
static void Main(string[] args)
{
int hWnd;
if( 0 < args.Length )
{
if (int.TryParse(args[0], out hWnd) == true)
{
COPYDATASTRUCT cds = new COPYDATASTRUCT();
cds.cbData = 0;
SendMessage(hWnd, WM_COPYDATA, IntPtr.Zero, ref cds);
}
}
Console.WriteLine("Hello");
Console.ReadLine();
}
}
}
ちなみに、
>起動失敗の場合:-1
とのことですが、応答を返すプログラムがつもりのBがそもそも起動していないのですから、応答することはできません。(死人に話しかけても返事がないのと同じ)