@JChild , Welcome to Microsoft Q&A, Since WPF does not have WndProc method to deal with messages, so we need to use HwndSource to get message from other apps.
I make a code example to send message from winform to wpf app, it works well.
Win32 code:
#define BTN_PLUS 100
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
{
CreateWindowEx(0, L"BUTTON", L"sendmessage", WS_CHILD | WS_VISIBLE, 130, 240, 125, 60,
hWnd, (HMENU)BTN_PLUS, GetModuleHandle(NULL), NULL);
break;
}
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
/* case BN_CLICKED*/
case 100:
{
int x = 58;
int y = 32;
HWND handle = FindWindow(NULL, L"MainWindow");
//MessageBoxA(hWnd, "Hello,world", "test1", WS_VISIBLE);
PostMessage(handle, WM_LBUTTONDOWN, 0, x + (y << 16));
PostMessage(handle, WM_LBUTTONUP, 0, x + (y << 16));
}
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
Wpf Code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.SourceInitialized += new EventHandler(MainWindow_SourceInitialized);
}
#region
public const int WM_GETTEXT = 0x0D;
public const int WM_SETTEXT = 0x0C;
public const int WM_SIZEING = 0x0214;
public const int WM_COPYDATA = 0x004A;
public const int WM_LBUTTONDBLCLK = 0x0203;
public const int WM_LBUTTONDOWN = 0x201;
public const int WM_LBUTTONUP = 0x202;
#endregion
#region
public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}
#endregion
void MainWindow_SourceInitialized(object sender, EventArgs e)
{
IntPtr hwnd = new WindowInteropHelper(this).Handle;
HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(WndProc));
}
//public const int WM_GETTEXT = 0x0D;
IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case WM_LBUTTONDOWN:
//txtUserName.Text = "Left button down";
MessageBox.Show("Left button down");
break;
case WM_LBUTTONUP:
//txtUserName.Text = "Left button up";
MessageBox.Show("Left button up");
break;
default:
{
break;
}
}
return IntPtr.Zero;
}
}
Tested result:
It could transfer the message successfully.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.