WinUI3 FindWindow() 不断返回 0x0000000000000000

问题描述 投票:0回答:1

我正在使用 winui3C# 构建两个应用程序作为发送方应用程序和接收方应用程序。 在发送者应用程序中,我在 buttonclicked 事件中使用了 findwindow() 和 send message() 。 在接收者应用程序中,我想在发送者应用程序发送消息时显示通知。 问题是 Findwindow() 结果是“0x0000000000000000”。 知道我留下了什么来做这件事吗?谢谢你。

这是我的发件人代码

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

private const uint WM_USER = 0x0400; // Custom message range for user-defined messages
private const int WM_MY_MESSAGE = (int)(WM_USER + 1); // Custom message identifier

 private async void SendMessageButton_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
 {
     try
     {
         // Find the window handle of the receiver app
         IntPtr hWnd = FindWindow(null, "com.receiver"); //namespace of receiver app

         if (hWnd != IntPtr.Zero)
         {
             // Send a message to the receiver app
             SendMessage(hWnd, (uint)WM_MY_MESSAGE, IntPtr.Zero, IntPtr.Zero);
             await ShowMessageDialog("Message sent to the receiver app.");
         }
         else
         {
             await ShowMessageDialog("Receiver app window not found.");
         }
     }
     catch (Exception ex)
     {
         await ShowMessageDialog("An error occurred: " + ex.Message);
     }
 }

我的接收者:

 private const int WM_MY_MESSAGE = 0x0400 + 1; // Custom message identifier
public MainPage()
{
    this.InitializeComponent();
    RegisterWindowMessage();
}
private void RegisterWindowMessage()
{
    // Register the custom window message
    RegisterWindowMessage("WM_MY_MESSAGE");
}

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int RegisterWindowMessage(string lpString);

private void Dispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args)
{
    // Handle the custom window message
    if (args.KeyStatus.RepeatCount == WM_MY_MESSAGE)
    {
        ShowNotification("Message received from sender app.");
    }
}

private async void ShowNotification(string message)
{
    var dialog = new MessageDialog(message);
    await dialog.ShowAsync();
}
c# winui-3
1个回答
0
投票

Window.Current 属性:桌面应用程序始终为此属性返回 null。

如果你想在winui3中检索窗口句柄,我建议你应该使用

GetWindowHandle
而不是
findWindow
。请参阅文档:检索窗口句柄

© www.soinside.com 2019 - 2024. All rights reserved.