kma*_*ks2 5 .net c# native user32 winforms
我有一个代码块,如:
IntPtr hWnd = new WindowInteropHelper(this).Handle;
HwndSource source = HwndSource.FromHwnd(hWnd);
source.AddHook(new HwndSourceHook(WndProc));
NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_CALL, IntPtr.Zero, IntPtr.Zero);
Run Code Online (Sandbox Code Playgroud)
这最初是在 WPF 应用程序中。但是,我需要在 WinForms 应用程序中复制该功能。此外,NativeMethods.PostMessage 只是映射到 user32.dll PostMessage:
[DllImport("user32")]
public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
Run Code Online (Sandbox Code Playgroud)
WindowInteropHelper/HwndSource/HwndSourceHook我可以在 WinForms 应用程序中使用1 比 1 的等价物吗?
基本点是:除了AddHook来源之外,您不需要任何东西。每个 WinForm 都有一个方法GetHandle(),可以为您提供 Window/Form 的句柄(您PostMessage已经自己找到了)。
太翻译了,AddHook您要么编写自己的类实现IMessageFilter(1),要么覆盖WndProc()(2)。
(1) 将在应用程序范围内接收消息,而不管您将它们发送到哪种表单,而 (2) 仅接收覆盖该方法的特定表单的消息。
我找不到关于 的任何信息WM_CALL,因为您必须将窗口消息指定为整数(通常为十六进制),所以这取决于您。
(1):
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public partial class Form1 : Form
{
[DllImport("user32")]
public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
//private const int WM_xxx = 0x0;
//you have to know for which event you wanna register
public Form1()
{
InitializeComponent();
IntPtr hWnd = this.Handle;
Application.AddMessageFilter(new MyMessageFilter());
PostMessage(hWnd, WM_xxx, IntPtr.Zero, IntPtr.Zero);
}
}
class MyMessageFilter : IMessageFilter
{
//private const int WM_xxx = 0x0;
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_xxx)
{
//code to handle the message
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
(2):
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public partial class Form 1 {
[DllImport("user32")]
public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
//private const int WM_xxx = 0x0;
//you have to know for which event you wanna register
public Form1()
{
InitializeComponent();
IntPtr hWnd = this.Handle;
PostMessage(hWnd, WM_xxx, IntPtr.Zero, IntPtr.Zero);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WMK_xxx)
{
//code to handle the message
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7391 次 |
| 最近记录: |