C # Implementation of custom message processing

Source: Internet
Author: User

As we all know, delegates and event mechanisms are a very important aspect of C # applications.

Microsoft's BCL class library has a nearly complete encapsulation of Windows controls, enabling application developers to write a sample program without even knowing the message loop.

However, even when Windows UI is programmed into the WPF era, the messaging mechanism still holds a pivotal role. You can say that without a message loop there is no windows. (Of course WPF is largely a encapsulation of D3D, which is not a WIN32 message loop in itself, but Micorsoft still provides support for WIN32 message mechanisms in WPF).

BCL2.0 's System.Windows.Forms namespace controls are a complete further encapsulation of the Win32 control, so the c#2.0 itself is based on the WIN32 message loop mechanism, and in some places, even with the help of messages when writing C # desktop applications, Otherwise, you may not be able to implement some functionality or be difficult to implement. For example, the Aplication class provides support for adding addmessagefilter, the control class emits several virtual methods similar to processCmdKey, and the control class implements the WndProc as virtual, So that control developers can easily override them.

No more nonsense. Consider a situation where an application is associated with a file type, and double-clicking a file of that type will open the document using that application. It's easy to implement that the program reads the file (possibly multiple) as a command-line parameter and now assumes that this is a multiple-document application, and if the application is running, then it is generally desirable to open the files with this existing program rather than re-enable a new instance of the program. This is common in Windows applications, such as opening a program source file with Visual Studio, opening another HTML document with IE7 (whether this can be configured to enable a new instance or open it with an existing instance), and so on. Suppose this software is developed with WIN32 or VC, it is easy to implement, look for an existing instance (process), if found, further look for its main window, send a message to it, transfer the file list, let it handle, the current routine ends. The main window handles this custom message, but if you're using C #, you might be stupid.

In fact, the above methods still apply in C # applications, and you can still customize messages in C #. This scenario is illustrated below. Suppose the last generated executable program is called "MyApplication.exe."

1using System;


2using System.Collections.Generic;


3using System.Diagnostics;


4using System.Runtime.InteropServices;


5using System.IO;


6using System.Reflection;


7using System.Windows.Forms;


8


9namespace MyApplication {


internal Static class program {


[STAThread]


private static void Main (string[] args) {


Application.enablevisualstyles ();


Application.setcompatibletextrenderingdefault (FALSE);


15


list<string> filelist = new list<string> ();


foreach (string filename in args) {


if (file.exists (filename)) {


filelist.add (filename);


20}


21}


22


if (! Singleinstancehelper.openfilesinpreviousinstance (Filelist.toarray ())) {


Application.Run (New Mywindow ());


25}


26}


27}


28


public class Mywindow:form {


protected override void WndProc (ref message msg) {


if (! Singleinstancehelper.prefiltermessage (ref msg, this)) {


base. WndProc (ref msg);


33}


34}


35}


36


Notoginseng internal Static class Singleinstancehelper {


private static readonly int custom_message = 0X400 + 2;


the private static readonly int result_files_handled = 2;


40


[DllImport ("user32.dll")]


The private static extern IntPtr SendMessage (IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);


43


[DllImport ("user32.dll")]


private static extern IntPtr SetForegroundWindow (IntPtr hWnd);


46


public static bool Openfilesinpreviousinstance (string[] filelist) {


int currentprocessid = Process.getcurrentprocess (). Id;


string currentfile = assembly.getentryassembly (). Location;


int number = new Random (). Next ();


Wuyi String fileName = Path.Combine (Path.gettemppath (), "SD" + number + ". tmp");


a try {


file.writealllines (FileName, filelist);


list<intptr> alternatives = new list<intptr> ();


foreach (Process p in Process.getprocessesbyname ("MyApplication")) {


if (p.id = = Currentprocessid) continue;


57


if (string. Equals (Currentfile, P.mainmodule.filename, stringcomparison.currentcultureignorecase)) {


IntPtr hWnd = p.mainwindowhandle;


if (hWnd!= intptr.zero) {


Long result = SendMessage (HWnd, Custom_message, New IntPtr (number), IntPtr.Zero). ToInt64 ();


if (result = = result_files_handled) {


) return true;


64}


65}


66}


67}


return false;


and finally {


File.delete (fileName);


71}


72}


73


internal static bool Prefiltermessage (ref message M, Form mainform) {


if (m.msg!= custom_message)


the return false;


77


Long filenumber = M.wparam.toint64 ();


M.result = new IntPtr (result_files_handled);


try {


Bayi MethodInvoker invoker = delegate {


SetForegroundWindow (Mainform.handle);


83};


Mainform.invoke (invoker);


string tempfilename = Path.Combine (Path.gettemppath (), "SD" + filenumber + ". tmp");


foreach (String file in File.ReadAllLines (TempFileName)) {


Invoker = delegate {


//Open the file


89};


Mainform.invoke (invoker);


91}


' catch (Exception) {


return false;


94}


95


return true;


97}


98}


99}

The sample program only allows the application to run an instance by examining the process, then customizing the message, sending a message through SendMessage to another instance of the program, which involves sending data between processes, and must use the type Marshal if sent directly. Marshal custom types are not allowed to be passed in C # (unless hooks are used). The easiest way to do this is to send a plastic random number directly, use this number to create a temporary file in the temporary folder, write the data, another instance of the program received the message, read the file to obtain the data, the corresponding processing, and then the temporary file was deleted, so that the data exchange between processes.

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.