프로젝트 1,2 를 사용하여 폼을 하나더 만들어서 단축키를 누르면 두번째 폼이 최상위로 나오게 만들었습니다.
버튼을 누르면 두번째폼이 나오게되는것 입니다 단축키는 프로젝트 2번과 같이 ctrl+q로 했고 이것은 button 1을
클릭하는 용도로 사용하였습니다.
코드입니다.
Form1.cs |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
RegisterHotKey(this.Handle, KEYid, KeyInform.Control, Keys.Q); //단축키 추가
}
//단축키
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr itp, int id, KeyInform fsInform, Keys vk);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr itp, int id);
const int KEYid = 31197;
public enum KeyInform
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
const int HOTKEYGap = 0x0312;
protected override void WndProc(ref Message message)
{
switch (message.Msg)
{
case HOTKEYGap:
Keys key = (Keys)(((int)message.LParam >> 16) & 0xFFFF); //눌러 진 단축키의 키
KeyInform modifier = (KeyInform)((int)message.LParam & 0xFFFF);//눌려진 단축키의 수식어
if ((KeyInform.Control) == modifier && Keys.Q == key)
{
this.button1.PerformClick();
}
break;
}
base.WndProc(ref message);
}
//폼 최상위로 띄우기
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string SClassName, string SWindowName);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr findname);
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr findname, int howShow);
private const int showNORMAL = 1;
private const int showMINIMIZED = 2;
private const int showMAXIMIZED = 3;
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
this.Visible = false;
// 윈도우 타이틀명으로 핸들을 찾는다
IntPtr findname = FindWindow(null, "Form2");
if (!findname .Equals(IntPtr.Zero))
{
// 프로그램이 최소화 되어 있다면 활성화 시킴
ShowWindowAsync(findname, showNORMAL);
// 윈도우에 포커스를 줘서 최상위로 만듬
SetForegroundWindow(findname);
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
UnregisterHotKey(this.Handle, KEYid);//단축키 제거
}
}
}
두번째 폼입니다.
첫번째 폼에서 버튼을 누르게 되면 나오게됩니다.
첫번째 폼의 visible을 껐기 때문에 이폼이 닫히면 Application.Exit();를 사용하여 프로젝트를 종료 하도록 했습니다.
Form2.cs |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
댓글