블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2738)
Unity3D (817)
Programming (475)
Python (8)
TinyXML (5)
STL (13)
D3D (3)
MFC (1)
C/C++ (54)
C++/CLI (45)
C# (250)
WinForm (6)
WPF (5)
Math (10)
A.I. (1)
Win32API (11)
Algorithm (3)
Design Pattern (7)
UML (1)
MaxScript (1)
FMOD (4)
FX Studio (1)
Lua (2)
Terrain (1)
Shader (3)
boost (2)
Xml (2)
JSON (4)
Etc (11)
Monad (1)
Html5 (4)
Qt (1)
Houdini (0)
Regex (11)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
05-03 00:02

Introduction

This class allows you to tap keyboard and mouse and/or to detect their activity even when an application runs in the background or does not have any user interface at all. This class raises common .NET events withKeyEventArgs and MouseEventArgs, so you can easily retrieve any information you need.

Background

There are a number of applications that run in the background and detect user inactivity to change their mode. For example, MSN Messenger (or any other messenger). I was going to write such an application, so I searched MSDN and found "exactly" what I needed: 318804 - HOW TO: Set a Windows Hook in Visual C# .NET. This article describes how to tap the mouse movement, but it works only when an application is active. At the end of this article, I found this explanation: "Global hook is not supported in .NET Framework. You cannot implement global hooks in Microsoft .NET Framework...". Anyway, I continued my research and found out that there are exceptions. There are WH_KEYBOARD_LL and WH_MOUSE_LL hooks that can be installed globally. So, I have basically replaced WH_MOUSE with WH_MOUSE_LL in the MSDN example, and it works.

The second step was to extract the information received into a .NET EventArgs and raise the appropriate events.

I found a similar article in CodeProject, under Global System Hooks in .NET by Michael Kennedy, but what I dislike is, there is an unmanaged DLL in C++ that is a main part of this solution. This unmanaged DLL is in C++, and a number of classes make it complicated to integrate it in my own tiny application.

Revisions

This article was posted in 2004 and updated in 2006. During all this time until now I receive a lot of positive feedback and recommendations. There were also a number of technology improvements like .NET Framework 3.5 or Visual Studio 2008. So I have decided to update it once more.

I have refactored and improved the solution, made it more flexible, stable and efficient. But this refactoring also had some drawbacks:

  1. Number of code lines and files has grown.
  2. Backward compatibility to older .NETs is lost.

That's why I attend to leave the old version also to be available for download.

Using the Code [Version 2]

The Simple Way

If you are developing a Windows Forms application and prefer drag & drop programming, there is a componentnamed GlobalEventProvider inside the assembly Gma.UserActivityMonitor.dll. Just drag and drop it to your form and create events using the property editor events tab.

The Alternative Way

Use events provided by the static class HookManager. Note that the sender object in events is alwaysnull.

For more usage hints, see the source code of the attached demo application.

Using the Code [Version 1]

To use this class in your application, you need to just create an instance of it and hang on events you would like to process. Hooks are automatically installed when the object is created, but you can stop and start listening using appropriate public methods.

 Collapse
UserActivityHook actHook;
void MainFormLoad(object sender, System.EventArgs e)
{
    actHook= new UserActivityHook(); // crate an instance

    // hang on events

    actHook.OnMouseActivity+=new MouseEventHandler(MouseMoved);
    actHook.KeyDown+=new KeyEventHandler(MyKeyDown);
    actHook.KeyPress+=new KeyPressEventHandler(MyKeyPress);
    actHook.KeyUp+=new KeyEventHandler(MyKeyUp);
}

Now, an example of how to process an event:

 Collapse
public void MouseMoved(object sender, MouseEventArgs e)
{
    labelMousePosition.Text=String.Format("x={0}  y={1}", e.X, e.Y);
    if (e.Clicks>0) LogWrite("MouseButton     - " + e.Button.ToString());
}

Changes and Updates from [Version 0] to [Version 1]

I'd like to thank you all for all the useful comments in the discussion forum. There were a lot of bugs and proposals posted after this article was published on 4th June, 2004. Over and over again came the same topics, and I had to refer to previous posts in the discussion, that is why I have decided to revise the code and publish a FAQ. Here is the list of the most important changes:

  • The project was converted into Visual Studio 2005
  • The problem with upper case characters is solved
  • Mouse wheel information is now included in event arguments
  • Better exception handling
  • Cancellation of keyboard events using the Handled property of event arguments
  • XML documentation of functions

FAQ [Version 1]

Question

The project cannot be run in Visual Studio .NET 2005 in debug mode because of an exception error caused by calling the SetWindowsHookEx. Why? Is it a problem of .NET 2.0?

Answer

The compiled release version works well so that cannot be a .NET 2.0 problem. To workaround, you just need to uncheck the check box in the project properties that says: "Enable Visual Studio hosting process". In the menu: Project -> Project Properties... -> Debug -> Enable the Visual Studio hosting process.

Question

I need to suppress some keystrokes after I have processed them.

Answer

Just set the e.Handled property to true in the key events you have processed. It prevents the keystrokes being processed by other applications.

Question:

Is it possible to convert your global hooks to application hooks which capture keystrokes and mouse movements only within the application?

Answer

Yes. Just use...

 Collapse
private const int WH_MOUSE = 7;
private const int WH_KEYBOARD = 2;

... everywhere, instead of:

 Collapse
private const int WH_MOUSE_LL = 14;
private const int WH_KEYBOARD_LL = 13;

Question

Does it work on Win98 (Windows ME, Windows 95)?

Answer

Yes and No. The global hooks WH_MOUSE_LL and WH_KEYBOARD_LL can be monitored only under Windows NT/2000/XP. In other cases, you can only use application hooks (WH_MOUSE and WH_KEYBOARD) which capture keystrokes and mouse movement only within the application.

Question

I have a long delay when closing applications using hooks by clicking the x button in the titlebar. If I close the application via another event (button click) for example, that works fine.

Answer

It's a known bug of Microsoft. It has to do with the Windows themes. If you disable the Windows themes, the problem goes away. Another choice is to have the hook code run in a secondary thread.

Question

How do I catch key combinations like Ctrl+Shift+A?

Answer

You'll have to track which keys have gone down but not up. Only the most recently pressed key keeps sendingKeyDown messages, but the others will still send a KeyUp when released. So if you make three flagsIsCtrlDown, IsShiftDown, and IsADown, and set them to true at KeyDown and false at KeyUp, the expression (IsCtrlDown && IsShiftDown && IsADown) will give you the required result.

Question

Does it works with .NET Framework 1.1 and Visual Studio 2003?

Answer

Yes. The file UserActivityHook.cs can be used without any changes, in a Visual Studio 2003 .NET 1.1 project.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

George Mamaladze

Software Developer (Senior)

Germany Germany

Member


출처 : http://www.codeproject.com/KB/cs/globalhook.aspx
반응형

'Programming > C#' 카테고리의 다른 글

[펌] 입력 문자 검사  (0) 2011.09.14
C# 관련 정보 사이트[MKEXDEV.NET]  (0) 2011.09.13
Array -> String  (0) 2011.05.09
SaveFileDialog  (0) 2011.03.25
DataGridView to XML  (0) 2011.03.23
Posted by blueasa
, |

Array -> String

Programming/C# / 2011. 5. 9. 02:12

요새 c#으로 삽질중이다.

 

오늘은 배열로 한 한시간 가까이 날려 먹은거 같은데;;

 

Array라는 타입이 있다. 모든 배열의 기초 클래스란다

요넘을 String[]로 옮기고 싶은 거다...

 

즉...

Array Buffer = new Array[0];

이런 녀석이 있다면

String[] szBuffer = Buffer;

이 짓을 하고 싶다는 거지;;

 

한참을 해맸지만 결론은 간단했다.

 

String[] szBuffer = (String)Buffer;

 

허탈하네 - _-;;



[출처]
 C#에서 배열|작성자 시네루진

반응형

'Programming > C#' 카테고리의 다른 글

C# 관련 정보 사이트[MKEXDEV.NET]  (0) 2011.09.13
Processing Global Mouse and Keyboard Hooks in C#  (0) 2011.05.13
SaveFileDialog  (0) 2011.03.25
DataGridView to XML  (0) 2011.03.23
ToolTip 사용하기  (0) 2011.02.11
Posted by blueasa
, |

SaveFileDialog

Programming/C# / 2011. 3. 25. 17:08
반응형

'Programming > C#' 카테고리의 다른 글

Processing Global Mouse and Keyboard Hooks in C#  (0) 2011.05.13
Array -> String  (0) 2011.05.09
DataGridView to XML  (0) 2011.03.23
ToolTip 사용하기  (0) 2011.02.11
C# TAB, 방향키, Control, Alt, Shift Key 입력 처리  (2) 2011.01.20
Posted by blueasa
, |

DataGridView to XML

Programming/C# / 2011. 3. 23. 17:37


음..테스트 안해봤지만 심플함. 해봐야지..
반응형
Posted by blueasa
, |

ToolTip 사용하기

Programming/C# / 2011. 2. 11. 18:31

버튼 설명하려고 하다보니 ToolTip을 쓰게됬는데 나중 되면 생각안날 것 같아서 메모!

 

 

 

1. 프로젝트 생성

2, ToolTip넣을 Control 삽입

 

3. ToolTip Control 추가 및 속성 변경

   (Name은 알아서 변경)

 

  풍선모양/Info icon

 

  

4. ToolTip정보 입력

 (생성자에 입력)

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //ToolTip
            toolTip1.SetToolTip(button1, "이것은 버튼입니다.");

        }
    }
}

 

 

 

 

* ToolTip속성 변경

(풍선모양 해제, Icon None)

 

 



출처 : http://www.cyworld.com/gpfhd/5429911

반응형
Posted by blueasa
, |
        다음 메쏘드를 이용하여 알아내면 됩니다.
       
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
       

        사용법은 아래 소스코드를 보시고 이해 하시면 될것 같네요..

       
        동시 키 눌림
은 아래와같이 OR (|) 연산자를 이용하시면 되는데..
        간혹 Ctrl + C, Ctrl + V, Ctrl + X 등이 캐치 되지 않는 경우가 있습니다.

        그럴경우는 툴박스나, 메뉴바, 컨텍스트메뉴 (마우스 오른쪽메뉴) 에서 해당 숏컷이 등록되어 있는지 확인하시고,
        등록이 되어 있다면, 해당 숏컷에 이벤트를 등록 해 주시면 됩니다.


        메소드를 보시면 제일 마지막에 
       
        return base.ProcessCmdKey(ref msg, keyData);
       

        이런 부분이 있습니다.

        저 부분이 다음 이벤트로 이벤트를 넘겨주는 역할을 하게 되는것이죠..

        즉 ProcessCmdKey 가 받은 이벤트를 오버라이딩하여 우리가 원하는 코드를 넣었으니,
        다시 원래 가야할 길로 보내주는겁니다.

        KeyDown 이나.. 그 전에 어떤 이벤트 핸들러가 있다면 그쪽으로 넘어가겠죠..;;;
        정확한 내용은 찾는데로 업뎃하겠습니다..


        예제 소스를 보시면 쉽게 이해가 되시리라 믿습니다.



        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.Down:
                case Keys.Up:
                case Keys.Right:
                case Keys.Left:
                case Keys.Control | Keys.Down:
                case Keys.Control | Keys.Up:
                case Keys.Control | Keys.Right:
                case Keys.Control | Keys.Left:
                    // 방향키, 혹은 컨트롤키 + 방향키가 입력되었을때
                    // 처리, 혹은 다른 메쏘드 호출을 여기에 적어주시면 됩니다.
                    break;

                case Keys.Control | Keys.X:
                    // 잘라내기 (Ctrl + X)
                    // 처리, 혹은 다른 메쏘드 호출을 여기에 적어주시면 됩니다.
                    break;

                case Keys.Control | Keys.C:
                    // 복사하기 (Ctrl + C)
                    // 처리, 혹은 다른 메쏘드 호출을 여기에 적어주시면 됩니다.
                    break;

                case Keys.Control | Keys.V:
                    // 붙여넣기 (Ctrl + V)
                    // 처리, 혹은 다른 메쏘드 호출을 여기에 적어주시면 됩니다.
                    break;

                default:
                    break;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }


반응형

'Programming > C#' 카테고리의 다른 글

DataGridView to XML  (0) 2011.03.23
ToolTip 사용하기  (0) 2011.02.11
[펌] 외부 응용프로그램 실행하기 (Process.Start 메서드) - CMD  (0) 2011.01.13
sendmessage in C#  (1) 2010.12.27
C# SendMessage Keypress  (1) 2010.12.26
Posted by blueasa
, |

윈도우를 종료
System.Diagnostics.Process.Start("cmd.exe","ShutDown.exe -s -f -t 00");


윈도우를 재부팅

System.Diagnostics.Process.Start("cmd.exe","ShutDown.exe -r -f -t 00");

 

특정 폴더 열기
System.Diagnostics.Process.Start("explorer.exe", "C:\Temp");

특정 사이트 열기
System.Diagnostics.Process.Start("explorer.exe", "http://www.naver.com");

 

도스명령어 실행

System.Diagnostics.Process.Start("cmd.exe","/c dir");

// cmd 옵션에 대해 더 알고싶으면.. c:>help cmd

 

Process.Start 메서드 사용형식
 

using System.Diagnostics;

//System.Diagnostics 네임스페이스는 시스템 프로세스, 이벤트 로그 및 성능 카운터와 상호 작용할 수 있는 클래스를 제공합니다.

 

public bool Start();
//이 Process 구성 요소의 StartInfo 속성으로 지정된 프로세스 리소스를 시작하거나 다시 사용하여 구성 요소에 연결합니다.

 

Process myProcess = new Process();
string myDocumentsPath =   Environment.GetFolderPath(Environment.SpecialFolder.Personal);
myProcess.StartInfo.FileName = myDocumentsPath + "
\MyFile.doc"; 
myProcess.StartInfo.Verb = "Print";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();

 

public static Process Start( ProcessStartInfo startInfo);
// ProcessStartInfo : 파일 이름 및 모든 명령줄 인수를 포함하여 프로세스를 시작하는 데 사용되는 정보
// 시작할 프로세스의 파일 이름 같은 프로세스 시작 정보가 포함된 매개 변수에 의해 지정된 
// 프로세스 리소스를 시작하고 해당 리소스를 새 Process 구성 요소에 연결합니다

 

ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
startInfo.WindowStyle = ProcessWindowStyle.Minimized;
startInfo.Arguments = "
www.naver.com";
Process.Start(startInfo);

 

public static Process Start(string fileName);
// fileName : 프로세스에서 실행될 응용 프로그램 파일 이름입니다.

//문서 또는 응용 프로그램 파일 이름을 지정하여 프로세스 리소스를 시작하고 해당 리소스를 새 Process 구성 요소에 연결합니다

 

Process.Start("IExplore.exe");

 

public static Process Start(string fileName, string arguments); 
// arguments : 프로세스를 시작할 때 전달할 명령줄 인수입니다

//응용 프로그램 이름 및 명령줄 인수 집합을 지정하여 프로세스 리소스를 시작하고 해당 리소스를 새 Process 구성 요소에 연결합니다.

 

Process.Start("IExplore.exe", "C:\myPath\myFile.htm");
Process.Start("IExplore.exe", "C:\myPath\myFile.asp");

 

 

Process 클래스

Process 구성 요소는 컴퓨터에서 실행 중인 프로세스에 대한 액세스를 제공합니다. 간단히 말해 프로세스란 실행 중인 응용 프로그램을 말합니다.

 

Process 구성 요소는 응용 프로그램의 시작, 중지, 제어 및 모니터링을 위한 유용한 도구입니다.
Process 구성 요소를 사용하면 실행 중인 프로세스의 목록을 얻거나 새로운 프로세스를 시작할 수 있습니다. 또한 Process 구성 요소를 사용하여 시스템 프로세스에도 액세스할 수 있습니다. 
Process 구성 요소를 초기화한 후에는 해당 구성 요소를 사용하여 실행 중인 프로세스에 대한 정보를 얻을 수 있으며 그러한 정보에는 스레드 집합, 로드된 모듈(.dll 및 .exe 파일), 프로세스가 사용하고 있는 메모리 양과 같은 성능 정보 등이 포함됩니다.

 

프로세스 구성 요소는 속성 그룹에 대한 정보를 한 번에 가져옵니다. Process 구성 요소가 특정 그룹의 한 멤버에 대한 정보를 가져올 때 해당 그룹의 나머지 속성 값이 캐싱되므로 Refresh 메서드를 호출하지 않는 한 그룹의 다른 멤버에 대한 새로운 정보를 가져오지 않습니다. 따라서 속성 값이 Refresh 메서드를 마지막으로 호출하여 얻은 속성 값과 같을 수 있습니다. 이러한 그룹 명세는 운영 체제에 따라 다릅니다.

 

더 자세한 사항은 Microsoft Visual Studio .NET 2003 도움말에서 Process 클래스를 참고하세요.

 

 

도스명령수행 프로그램 


 

[전체소스]


using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Diagnostics;

using System.IO;

using System.Threading;


namespace mouseEvents

{


    public class Form1 : System.Windows.Forms.Form

    {

        private System.Windows.Forms.TextBox textBox1;

        private System.Windows.Forms.Label label2;

        private System.ComponentModel.IContainer components;

        private System.Windows.Forms.TextBox tbComm;

        private System.Windows.Forms.Button btnExec;



        public Form1()

        {

            InitializeComponent();

        }


        protected override void Dispose( bool disposing )

        {

            if( disposing )

            {

                if (components != null)

                {

                    components.Dispose();

                }

            }

            base.Dispose( disposing );

        }


        #region Windows Form Designer generated code

        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

            this.label2 = new System.Windows.Forms.Label();

            this.tbComm = new System.Windows.Forms.TextBox();

            this.btnExec = new System.Windows.Forms.Button();

            this.textBox1 = new System.Windows.Forms.TextBox();

            this.SuspendLayout();

            //

            // label2

            //

            this.label2.Location = new System.Drawing.Point(8, 8);

            this.label2.Name = "label2";

            this.label2.Size = new System.Drawing.Size(72, 17);

            this.label2.TabIndex = 5;

            this.label2.Text = "도스명령어:";

            //

            // tbComm

            //

            this.tbComm.Location = new System.Drawing.Point(80, 8);

            this.tbComm.Name = "tbComm";

            this.tbComm.Size = new System.Drawing.Size(355, 21);

            this.tbComm.TabIndex = 6;

            this.tbComm.Text = "";

            //

            // btnExec

            //

            this.btnExec.Location = new System.Drawing.Point(440, 8);

            this.btnExec.Name = "btnExec";

            this.btnExec.Size = new System.Drawing.Size(104, 25);

            this.btnExec.TabIndex = 1;

            this.btnExec.Text = "실행";

            this.btnExec.Click += new System.EventHandler(this.button2_Click);

            //

            // textBox1

            //

            this.textBox1.AcceptsReturn = true;

            this.textBox1.AcceptsTab = true;

            this.textBox1.Location = new System.Drawing.Point(8, 32);

            this.textBox1.Multiline = true;

            this.textBox1.Name = "textBox1";

            this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;

            this.textBox1.Size = new System.Drawing.Size(528, 312);

            this.textBox1.TabIndex = 2;

            this.textBox1.Text = "";

            //

            // Form1

            //

            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

            this.ClientSize = new System.Drawing.Size(547, 350);

            this.Controls.Add(this.tbComm);

            this.Controls.Add(this.label2);

            this.Controls.Add(this.textBox1);

            this.Controls.Add(this.btnExec);

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

            this.MaximizeBox = false;

            this.Name = "Form1";

            this.Text = "Process Class";

            this.ResumeLayout(false);


        }

        #endregion


        [STAThread]

        static void Main()

        {

            Application.Run(new Form1());

        }


        private void button2_Click(object sender, System.EventArgs e)

        {

            this.start();

        }


        private void start()

        {


            //Network 변수

            StreamWriter DosWriter;

            StreamReader DosRedaer;

            StreamReader ErrorReader;

           

            //프로세스 생성및 초기화

            Process DosPr = new Process();

           

            ProcessStartInfo psI = new ProcessStartInfo("cmd");

            psI.UseShellExecute = false;

            psI.RedirectStandardInput = true;

            psI.RedirectStandardOutput = true;

            psI.RedirectStandardError = true;

            psI.CreateNoWindow = true;



            //명령 실행

            DosPr.StartInfo = psI;

            DosPr.Start();

            DosWriter = DosPr.StandardInput;

            DosRedaer = DosPr.StandardOutput;

            ErrorReader = DosPr.StandardError;


            DosWriter.AutoFlush = true;


            DosWriter.WriteLine(tbComm.Text);

           

            DosWriter.Close();


            //출력

            textBox1.Text = DosRedaer.ReadToEnd();

            textBox1.Text += ErrorReader.ReadToEnd();


        }

    }

}



  작성자 : HOONS(박경훈)
  이메일 : tajopkh@hanmail.net

출처 : http://www.cyworld.com/nowy/192742


[출처 : http://skql.tistory.com/510]

반응형
Posted by blueasa
, |

sendmessage in C#

Programming/C# / 2010. 12. 27. 01:42
1         [DllImport("user32.dll", SetLastError = true)]  
2         static extern IntPtr FindWindow(string lpClassName, string lpWindowName);  
3  
4         [DllImport("user32.dll", SetLastError = true)]  
5         static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);  
6  
7         [DllImport("user32.dll")]  
8         private static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);  
9  
10         static void Main(string[] args)  
11         {  
12             // Use this to send key strokes  
13             const int WM_KEYDOWN = 0x100;  
14             IntPtr windowHandle = FindWindow("NOTEPAD"null);  
15             IntPtr editHandle = FindWindowEx(windowHandle, IntPtr.Zero, "EDIT"null);  
16             PostMessage(editHandle, WM_KEYDOWN, 'A', 0);  
17             Console.ReadKey();  
18         }

1         [DllImport("user32.dll")]  
2         public static extern int SendMessage(int hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPStr)] string lParam);  
3  
4         [DllImport("user32.dll", SetLastError = true)]  
5         static extern IntPtr FindWindow(string lpClassName, string lpWindowName);  
6  
7         [DllImport("user32.dll", SetLastError = true)]  
8         static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);  
9  
10         static void Main(string[] args)  
11         {  
12             const int WM_SETTEXT = 0x0C;  
13  
14             IntPtr windowHandle = FindWindow("NOTEPAD"null);  
15             IntPtr editHandle = FindWindowEx(windowHandle, IntPtr.Zero, "EDIT"null);  
16             string textToSendToFile = "Input here your text";  
17             SendMessage((int)editHandle, WM_SETTEXT, 0, textToSendToFile);  
18  
19             Console.ReadKey();  
20         }


반응형
Posted by blueasa
, |

C# SendMessage Keypress

Programming/C# / 2010. 12. 26. 23:45
#region Function Imports
 
       
[DllImport("user32.dll")]
       
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
 
       
[DllImport("user32.dll")]
       
static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
 
       
#endregion
 
       
#region Constants
 
       
// Messages
       
const int WM_KEYDOWN = 0x100;
       
const int WM_KEYUP = 0x101;
       
const int WM_CHAR = 0x105;
       
const int WM_SYSKEYDOWN = 0x104;
       
const int WM_SYSKEYUP = 0x105;
 
       
#endregion
 
       
public static void SendKey(string wName, Keys key)
       
{
           
IntPtr hWnd = FindWindow(null, wName);
 
           
SendMessage(hWnd, WM_KEYDOWN, Convert.ToInt32(key), 0);
           
SendMessage(hWnd, WM_KEYUP, Convert.ToInt32(key), 0);
       
}
 
       
public static void SendSysKey(string wName, Keys key)
       
{
           
IntPtr hWnd = FindWindow(null, wName);
 
           
SendMessage(hWnd, WM_SYSKEYDOWN, Convert.ToInt32(key), 0);
           
SendMessage(hWnd, WM_SYSKEYUP, Convert.ToInt32(key), 0);
       
}
 
       
public static void SendChar(string wName, char c)
       
{
           
IntPtr hWnd = FindWindow(null, wName);
 
           
SendMessage(hWnd, WM_CHAR, (int)c, 0);
       
}


반응형
Posted by blueasa
, |
[Korean]

1) CheckBox 생성

2) CheckBox - 속성 - Appearance 값을 Normal -> Button으로 변경

3) 사이즈 조절 하려면 CheckBox - 속성 - AutoSize = false 로 변경



[English]

1) Create CheckBox

2) CheckBox - Attribute(or Preference?) - Appearance Value : Normal -> Button

3) Adjust Size : CheckBox - Attribute(or Preference?) - AutoSize Value : false

반응형

'Programming > C#' 카테고리의 다른 글

sendmessage in C#  (1) 2010.12.27
C# SendMessage Keypress  (1) 2010.12.26
Microsoft Win32 to Microsoft .NET Framework API Map  (0) 2010.12.10
경로명,확장자 분리 함수 등등  (0) 2010.12.09
C# 디폴트 파라미터 따라하기  (0) 2010.12.03
Posted by blueasa
, |