Visual C # create a pop-up window to close the program

Source: Internet
Author: User

The pop-up window killer is a program that can automatically close the IE pop-up window. It works in the system tray, checks the IE window at a certain interval, and closes the pop-up window. Finally, the pop-up window can be killed by using hotkeys.

Although there are similar programs written in C ++, this article describes how to use C # To implement these functions, in addition, the solution described in this article is faster in the search window.

This is a brand new topic. We can see many similar programs on the Internet. However, I still want to take this opportunity to explain how some of the following technologies are implemented in C:

System Tray
Program Switching
Timing Control
Search window
System hotkey

Generate a system tray Program

First, generate a new C # Windows Form program and drag the policyicon control from the toolbox to the Form, as shown in:

Add a tray in the C # windows Form program

To ensure that the icon of the system tray is consistent with the icon of the application, we use a common icon file a. ico to set the icon of the system tray and the icon of the application.

To prevent the program from being displayed on the toolbar, we can set the visible attribute of the form to false, which can be directly implemented in the form attribute window.

This. ShowInTaskbar = false;

So far, the system tray has been basically good, but we have not set the right-click menu, and there is no function to display and hide the program.

Program Switching

First, the main form of the program can be displayed or hidden based on different States. In addition, we can use WindowState to set the status of the form:
Public void HideApp ()
{
This. WindowState = FormWindowState. Minimized;
Hide ();
}
Public void ShowApp ()
{
Show ();
This. WindowState = FormWindowState. Normal;
}
An interesting feature is that the program does not exit when the user closes the form. To implement this function, we must rewrite the OnClosing event of the form.

Protected override void OnClosing (CancelEventArgs e)
{
// Use Minimization instead of closing operation d
E. Cancel = true;
// Minimize and hide the form
This. WindowState = FormWindowState. Minimized;
Hide ();
}
Of course, we must provide a required exit method, which can be implemented in the exit of the right-click menu of the tray,
Private void menu_App_Exit (object sender, System. EventArgs e)
{
NativeWIN32.UnregisterHotKey (Handle, 100 );
// Hide the tray
Policyicon1.visible = false;
Application. Exit ();
}
Right-click menu

Adding a right-click menu is basically the same as adding a tray. You can add a context menu from the toolbox. The right-click menu will pop up automatically when you right-click the menu.

After setting the right-click menu, we need to enable or disable the right-click menu based on different situations. This can be set by BeforePopup in the menu. Enabled attribute.

Private void menu_App_BeforePopup (object sender, System. EventArgs e)
{
If (this. WindowState = FormWindowState. Minimized)
{
App_Show.Enabled = true;
App_Hide.Enabled = false;
}
Else
{
App_Show.Enabled = false;
App_Hide.Enabled = true;
}
}
Timing Tool

The. Net Framework Timer can implement the same functions as the system's Win32 timer. What we need to do is set a timer and set the attributes reasonably.
M_Timer = new System. Timers. Timer (); // explicit namespace (Timer also in System. Threading)
M_Timer.Elapsed + = new ElapsedEventHandler (OnTimerKillPopup );
M_Timer.Interval = m_nInterval; // for instance 3000 milliseconds
M_Timer.Enabled = true; // start timer

Protected void OnTimerKillPopup (Object source, ElapsedEventArgs e)
{
M_Timer.Enabled = false; // pause the timer

FindPopupToKill ();

M_Timer.Enabled = true;
}
Local win32 form search

The implementation principle of this program is as follows: first check all the title of the IE window, and then compare it with the existing list. If there is the same title, we close the window.

According to the above method, we use KillPopup () to check every n seconds. Unfortunately, we cannot use security code to complete all the work. We can use System. Diagnostics. Proces to check all IE processes and obtain the main form. However, each IE process can open several windows. Although each form is related to one process, there is no way to match each form with the process.

A feasible method to use system. diagnostics. process lists all running processes, and then system. diagnostics. processthreadcollection to get their. threads attribute. To get the thread ID, we use Win32 API enumthreadwindows (DWORD threadid, wndenumproc lpfn, lparam) to implement it. This is a call back function, it can list forms related to processes. After obtaining the form handle, we can use another API function getwindowtext (hwnd,/* out */lptstr lpstring, int nmaxcount) to obtain the Form title, then, based on the existing form, call the API function sendmessage (hwnd, int MSG, int wparam, int lparam) to close the window. The Demo code is as follows:

Process [] myprocesses = process. getprocessesbyname (\ "iexplore \");

Foreach (process myprocess in myprocesses)
{
Findpopuptokill (myprocess );
}

Protected void findpopuptokill (PROCESS p)
{
// Traverse all threads and enum all windows attached to the thread
Foreach (processthread t in P. threads)
{
Int threadid = T. ID;

Nativewin32.enumthreadproc callbackproc =
New NativeWIN32.EnumThreadProc (MyEnumThreadWindowsProc );
NativeWIN32.EnumThreadWindows (threadId, callbackProc, IntPtr. Zero/* lParam */);
}
}

// Callback used to enumerate Windows attached to one of the threads
Bool MyEnumThreadWindowsProc (IntPtr hwnd, IntPtr lParam)
{

Public const int WM_SYSCOMMAND = 0x0112;
Public const int SC _CLOSE = 0xF060;

// Get window caption
NativeWIN32.STRINGBUFFER sLimitedLengthWindowTitle;
NativeWIN32.GetWindowText (hwnd, out sLimitedLengthWindowTitle, 256 );

String sWindowTitle = sLimitedLengthWindowTitle. szText;
If (sWindowTitle. Length = 0) return true;

// Find this caption in the list of banned captions
Foreach (ListViewItem item in listView1.Items)
{
If (swindowtitle. startswith (item. Text ))
Nativewin32.sendmessage (hwnd, nativewin32.wm _ SYSCOMMAND,
Nativewin32. SC _ close,
Intptr. Zero); // try Soft kill
}

Return true;
}

Public class nativewin32
{
Public Delegate bool enumthreadproc (intptr hwnd, intptr lparam );

[Dllimport (\ "user32.dll \", charset = charset. Auto)]
Public static extern bool enumthreadwindows (INT threadid, enumthreadproc pfnenum, intptr lparam );

// Used for an output lpctstr parameter on a method call
[Structlayout (layoutkind. Sequential, charset = charset. Auto)]
Public struct stringbuffer
{
[Financialas (unmanagedtype. byvaltstr, sizeconst = 256)]
Public String sztext;
}

[DllImport (\ "user32.dll \", CharSet = CharSet. Auto)]
Public static extern int GetWindowText (IntPtr hWnd, out STRINGBUFFER ClassName, int nMaxCount );

[DllImport (\ "user32.dll \", CharSet = CharSet. Auto)]
Public static extern int SendMessage (IntPtr hWnd, int msg, int wParam, int lParam );
}
The above method is good in performance, because it filters out other non-IE Windows. however, we can use a simpler method to call the API findjavaswex (HWND hWndParent, HWND hWndNext,/* in */LPCTSTR szClassName,/* in */LPCTSTR szWindowTitle) method. we can use registered window class name to find the IE window (IEFrame is the identifier of all open IE ).

Protected void FindPopupToKill ()
{
IntPtr hParent = IntPtr. Zero;
IntPtr hNext = IntPtr. Zero;
String sClassNameFilter = \ "IEFrame \"; // class of all IE Windows
Do
{
HNext = nativewin32.find1_wex (hParent, hNext, sClassNameFilter, IntPtr. Zero );

// We \ 've got a hwnd to play
If (! HNext. Equals (IntPtr. Zero ))
{
// Get window caption
NativeWIN32.STRINGBUFFER sLimitedLengthWindowTitle;
NativeWIN32.GetWindowText (hNext, out sLimitedLengthWindowTitle, 256 );

String sWindowTitle = sLimitedLengthWindowTitle. szText;
If (sWindowTitle. Length> 0)
{
// Find this caption in the list of banned captions
Foreach (ListViewItem item in listView1.Items)
{
If (sWindowTitle. StartsWith (item. Text ))
NativeWIN32.SendMessage (hNext, NativeWIN32.WM _ SYSCOMMAND,
NativeWIN32. SC _ CLOSE,
IntPtr. Zero); // try soft kill
}
}
}
}
While (! HNext. Equals (IntPtr. Zero ));

}

Public class nativewin32
{
[Dllimport (\ "user32.dll \", charset = charset. Auto)]
Public static extern intptr find1_wex (intptr parent/* hwnd */,
Intptr next/* hwnd */,
String sclassname,
Intptr swindowtitle );

}
Download Code:

Demo program:

Registration System hotkey

System hotkeys are very useful for applications such as pop-up killer. CTRL + Shift + J is the default hotkey.

Speaking of implementation, we continue to use registerhotkey (hwnd, int ID, uint fsmodifiers, uint vkey ). Complete the following code:

Public void sethotkey (Keys C, bool bctrl, bool bshift, bool Balt, bool bwindows)
{
M_hotkey = C;
M_ctrlhotkey = bctrl;
M_shifthotkey = bshift;
M_althotkey = Balt;
M_winhotkey = bwindows;

// Update hotkey
NativeWIN32.KeyModifiers modifiers = NativeWIN32.KeyModifiers. None;
If (m_ctrlhotkey)
Modifiers | = NativeWIN32.KeyModifiers. Control;
If (m_shifthotkey)
Modifiers | = NativeWIN32.KeyModifiers. Shift;
If (m_althotkey)
Modifiers | = NativeWIN32.KeyModifiers. Alt;
If (m_winhotkey)
Modifiers | = NativeWIN32.KeyModifiers. Windows;

NativeWIN32.RegisterHotKey (Handle, 100, modifiers, m_hotkey); // Keys. J );
}
Generally, it takes a few steps to register the hotkey.

/* ------- Using HOTKEYs in a C # application -------

-- Code snippet by James J Thompson --

In Form load: Ctrl + Shift + J

Bool success = RegisterHotKey (Handle,
100,
KeyModifiers. Control | KeyModifiers. Shift,
Keys. J );
In form closing:

UnregisterHotKey (Handle, 100 );

How to handle hotkeys:

Protected override void WndProc (ref Message m)
{
Const int WM_HOTKEY = 0x0312;

Switch (m. Msg)
{
Case WM_HOTKEY:

MessageBox. Show (\ "Hotkey pressed \");

ProcessHotkey ();

Break;
}
Base. WndProc (ref m );
}

Public class NativeWIN32
{
[DllImport (\ "user32.dll \", SetLastError = true)]
Public static extern bool RegisterHotKey (IntPtr hWnd, // handle to window
Int id, // hot key identifier
KeyModifiers fsModifiers, // key-modifier options
Keys vk // virtual-key code
);

[DllImport (\ "user32.dll \", SetLastError = true)]
Public static extern bool UnregisterHotKey (IntPtr hWnd, // handle to window
Int id // hot key identifier
); Flags ()]
Public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}

}
------- Using HOTKEYs in a C # application -------*/

After pressing the hot key, the process is as follows: first, use HWND GetForegroundWindow () to obtain the form, and then capture the Form title, GetWindowText (HWND hwnd,/* out */LPTSTR lpString, int nMaxCount ). the details are as follows:

Protected void ProcessHotkey ()
{
IntPtr hwnd = NativeWIN32.GetForegroundWindow ();
If (! Hwnd. Equals (IntPtr. Zero ))
{
NativeWIN32.STRINGBUFFER sWindowTitle;
NativeWIN32.GetWindowText (hwnd, out sWindowTitle, 256 );

If (sWindowTitle. szText. Length> 0)
AddWindowTitle (sWindowTitle. szText); // add to the ListView (Form)
}
}


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.