C # Development Example-Custom screenshot tool (ii) Create project, register hotkey, display screenshot main window

Source: Internet
Author: User
Tags visual studio 2010





Development environment



Operating system: Windows Server R2



Integrated development Environment (IDE): Microsoft Visual Studio 2010



Development language: C #



Create a project



The new project of the document






The. NET framework can choose either version 2.0 or version 4.0;



Project type selection: Windows Forms application



Enter the project name to determine






The project was created successfully, such as:






Modify main Form Properties



Modify the form's "FormBorderStyle" property to "none" to implement a form without Borders






After the modification, the window designer appears as follows:






Press to modify the other properties, and the property values in bold are the modified






Property Description:



Showicon=false, the icon for the form is not displayed;



Showintaskbar=false, so that the form does not appear in the Windows taskbar;



Sizegripstyle=hide, disable drag the lower right corner of the form can change the size of the function;



windowsstate=minimized, the window is minimized after starting;



After setting these properties, compile, run, program is in the running state, but can not see the program window;



Implementing Hotkey Functions



Here you need to use WINDOWSAPI



Registration Hotkey: RegisterHotKey



This function defines a system-wide Hotkey . function prototype: BOOL RegisterHotKey (HWND hwnd,int id,uint fsmodifiers,uint VK);



Cancel Hotkey Registration: Unregisterhotkey



This function frees the hot key that was previously enlisted by the calling thread.



Get Hotkey ID:globaladdatom



Applies only to desktop applications.



Adds a string to the global atomic table and returns the unique identifier (Atom Atom) of the string.



API and local variable definitions:


/// <summary>

/// Add a string to the global atom table and return a unique identifier for this string (atomic ATOM).

/// </summary>

/// <param name="lpString">a string set by yourself</param>

/// <returns></returns>

[System.Runtime.InteropServices.DllImport("Kernel32.dll")]

Public static extern Int32 GlobalAddAtom(string lpString);

 

/// <summary>

/// Register hotkey

/// </summary>

/// <param name="hWnd"></param>

/// <param name="id"></param>

/// <param name="fsModifiers"></param>

/// <param name="vk"></param>

/// <returns></returns>

[System.Runtime.InteropServices.DllImport("user32.dll")]

Public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, Keys vk);

 

/// <summary>

/// Cancel hotkey registration

/// </summary>

/// <param name="hWnd"></param>

/// <param name="id"></param>

/// <returns></returns>

[System.Runtime.InteropServices.DllImport("user32.dll")]

Public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

 

/// <summary>

/// hotkey ID

/// </summary>

Public int hotKeyId = 100;

 

/// <summary>

/// Hotkey mode: 0=Ctrl + Alt + A, 1=Ctrl + Shift + A

/// </summary>

Public int HotKeyMode = 1;

 

/// <summary>

/// Type of control key

/// </summary>

Public enum KeyModifiers : uint

{

    None = 0,

    Alt = 1,

    Control = 2,

    Shift = 4,

    Windows = 8

}

 

/// <summary>

/// Image to save the entire screen that was intercepted

/// </summary>

Protected Bitmap screenImage;


Register Hotkey:


Private void Form1_Load(object sender, EventArgs e)

{

     //Hide the window

     this.Hide();

 

     / / Register shortcuts

     //Note: The legal range of HotKeyId is between 0x0000 and 0xBFFF. The value obtained by GlobalAddAtom function is between 0xC000 and 0xFFFF, so 0xC000 is subtracted to meet the call requirements.

     this.hotKeyId = GlobalAddAtom("Screenshot") - 0xC000;

     If (this.hotKeyId == 0)

     {

         / / If the acquisition fails, set a default value;

         this.hotKeyId = 0xBFFE;

     }

 

     If (this.HotKeyMode == 0)

     {

         RegisterHotKey(Handle, hotKeyId, (uint)KeyModifiers.Control | (uint)KeyModifiers.Alt, Keys.A);

     }

     Else

     {

         RegisterHotKey(Handle, hotKeyId, (uint)KeyModifiers.Control | (uint)KeyModifiers.Shift, Keys.A);

     }

}


Hotkey Response Function:


/// <summary>

/// Handling shortcut events

/// </summary>

/// <param name="m"></param>

Protected override void WndProc(ref Message m)

{

     //if (m.Msg == 0x0014)

     //{

     // return; // disable clear background message

     //}

     Const int WM_HOTKEY = 0x0312;

     Switch (m.Msg)

     {

         Case WM_HOTKEY:

             ShowForm();

             Break;

         Default:

             Break;

     }

     base.WndProc(ref m);

}


Window Implementation principle



The window is actually a full-screen top-level window with no borders, no menus, and no toolbars.



When the hotkey is pressed, the program first gets the picture of the entire screen, saves it to the "screenimage" variable, then adds a mask layer, sets it as the background of the form, sets the window size to the size of the main screen, and displays the window; it feels like a translucent mask layer on the desktop.



The code is as follows:


/// <summary>

/// If the window is visible, the window is hidden;

/// Otherwise the window is displayed

/// </summary>

Protected void ShowForm()

{

    If (this.Visible)

    {

        this.Hide();

    }

    Else

    {

        Bitmap bkImage = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height);

        Graphics g = Graphics.FromImage(bkImage);

        g.CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.AllScreens[0].Bounds.Size, CopyPixelOperation.SourceCopy);

        screenImage = (Bitmap)bkImage.Clone();

        g.FillRectangle(new SolidBrush(Color.FromArgb(64, Color.Gray)), Screen.PrimaryScreen.Bounds);

        this.BackgroundImage = bkImage;

 

        this.ShowInTaskbar = false;

        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

        this.Width = Screen.PrimaryScreen.Bounds.Width;

        this.Height = Screen.PrimaryScreen.Bounds.Height;

        this.Location = Screen.PrimaryScreen.Bounds.Location;

 

        this.WindowState = FormWindowState.Maximized;

        this.Show();

    }

}


Cancel Hotkey Registration



To cancel the hotkey registration when closing the window, the code is as follows:


/// <summary>

/// Verify when the window is closing

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

Private void Form1_FormClosing(object sender, FormClosingEventArgs e)

{

     If (e.CloseReason == CloseReason.ApplicationExitCall)

     {

         e.Cancel = false;

         UnregisterHotKey(this.Handle, hotKeyId);

     }

     Else

     {

         this.Hide();

         e.Cancel = true;

     }

} 


Here, the Hotkey Registration, window display and other functions have been basically completed.



Note: It is a good idea to add a button to the form to close or hide the window when testing this code, because the window is full-screen and cannot respond to the ESC key, so you can end the process exit only through Task Manager. It is a good idea to add a Label control on the form to display the required variable information, because the window is the top-level full-screen window, and the breakpoint is hit with no way to manipulate vs.


Related Article

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.