Example of a WPF Implementation WinForm window message WndProc

Source: Internet
Author: User
Tags mscorlib

Yesterday in the project development, encountered the operation of the USB port pull plug, want to be in the program, the implementation of the COM port pull plug monitoring, but the general WndProc is implemented in WinForm, so query how WPF is how to achieve.

The following methods are available for testing:

1, the definition of USB message structure

USB message Definition
public const int wm_device_change = 0x219;
public const int dbt_devicearrival = 0x8000;
public const int dbt_device_remove_complete = 0x8004;
Public Const UInt32 Dbt_devtyp_port = 0x00000003;
[StructLayout (LayoutKind.Sequential)]
struct DEV_BROADCAST_HDR
{
Public UInt32 dbch_size;
Public UInt32 Dbch_devicetype;
Public UInt32 dbch_reserved;
}
[StructLayout (LayoutKind.Sequential)]
protected struct dev_broadcast_port_fixed
{
public UINT Dbcp_size;
public UINT Dbcp_devicetype;
public UINT dbcp_reserved;
Variable?length Field Dbcp_name is declared the C header file.
}

2. Define Hook Method: WndProc


<summary>
Check the USB port plug
</summary>
<param name= "M" ></param>
Public IntPtr WndProc (IntPtr hwnd, int msg, IntPtr wParam, IntPtr LParam, ref BOOL handled)
{
if (msg = = Wm_device_change)//Capture unplug message for USB device Wm_devicechange
{
Switch (Wparam.toint32 ())
{
Case DBT_DEVICE_REMOVE_COMPLETE://USB Pull out
Break
Case DBT_DEVICEARRIVAL://USB insert get corresponding serial name
Dev_broadcast_hdr DBHDR = (DEV_BROADCAST_HDR) marshal.ptrtostructure (LParam, typeof (DEV_BROADCAST_HDR));
if (Dbhdr.dbch_devicetype = = Dbt_devtyp_port)
{
String portname = Marshal.ptrtostringuni (INTPTR) (Lparam.toint32 () + marshal.sizeof (typeof (Dev_broadcast_port_fixed ))));
Console.WriteLine ("Port" + portname + "' arrived.");
}
Break
}
}
return hwnd;
}
3, in the loaded, registration of this method

HwndSource Source = presentationsource.fromvisual (this) as HwndSource;
if (source!= null) source. Addhook (WNDPROC);


Extended reading:

Introduction to Marshal.structuretoptr Method

1. Function and location


Marshaling data from managed objects to unmanaged memory blocks, belonging to the. NET Framework class Library
Namespaces: System.Runtime.InteropServices
Assembly: mscorlib (in mscorlib.dll)
2. Grammar

                                             
C #:
      [ComVisibleAttribute ( true)] public static void StructureToPtr (Object structure,intptr ptr,bool fdeleteold);
C + +:
      [ComVisibleAttribute (True)]public:static void StructureToPtr (object^ Structure, IntPtr PTR, bool fdeleteold);
3. Parameter Description                                              

Structure: A managed object that contains the data to marshal. The object must be an instance of the formatted class.
PTR: A pointer to an unmanaged block of memory that must be assigned before this method is called.
fDeleteOld: Set to True to call this method on the PTR parameter before executing the Marshal.destroystructure method. Note that passing false can cause a memory leak.
4. Abnormal


Exception type: ArgumentException
Condition: structrue parameter is generic type
5. Notes

StructureToPtr copies the contents of the structure to the block of allocated memory that the PTR parameter points to. If the fDeleteOld argument is true, the embedding point is used
The appropriate deletion API on the needle deletes the buffer originally pointed to by PTR, but the buffer must contain valid data. This method is the middle finger of a mirrored managed class
Performs cleanup work for each reference field that is set.

Suppose the PTR points to an unmanaged block of memory. The layout of this memory block is described by the appropriate managed class structure. StructureToPtr the field value from the structure envelope
Sent to the pointer. Suppose the PTR block contains a reference field that points to a string buffer that currently contains "ABC". Suppose the corresponding field on the managed side is a string containing "vwxyz." Without notifying it, StructureToPtr allocates a new unmanaged buffer to hold "vwxyz" and hooks it to the PTR block. This discards the old buffer "abc" from drifting without releasing it back to the unmanaged heap. Finally, you will get an orphaned buffer that represents a memory leak in your code. If you set the fDeleteOld parameter to True, StructureToPtr releases the buffer that saved "ABC" before continuing to assign a new buffer to "vwxyz".
Reference:

After the visual handle is created (such as onload, onsourceinitialized code), use the following method:

Method One:

HwndSource source =presentationsource.fromvisual (this) as HwndSource;
if (source!= null) source. Addhook (WNDPROC);

Method Two:

HwndSource Source =hwndsource.fromhwnd New Windowinterophelper (this). Handle);
if (source!= null) source. Addhook (WNDPROC);
Note: This in both methods can be changed to a visual object.

You can then hwndsourcehook the WndProc method of the delegate:

Private IntPtr WndProc (IntPtr hwnd,int msg,intptr wparam,intptr bool lparam,ref)
{
Handle messages ...
return IntPtr.Zero;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.