PDA

View Full Version : [Tutorial] Viết một chương trình đọc nội dung của WordPad hoặc NotePad đang mở (DataGrabber)



dotri84
22-02-2011, 22:25
Chương trình này mình viết để đọc nội dung text trong chương trình WordPad và NotePad đang mở trên máy. Chương trình này cần improve để đọc được text trên Microsoft Word, đọc 2 file cùng tên sẽ có problem :D, ... Mình muốn chia sẻ cùng các bạn :present:

Constructor for Form


public Form1()
{
InitializeComponent();
dict = new Dictionary<string, string[]>();

// Build the dictionary for supported programs
dict.Add("notepad", new string[] { "NotePad", "EDIT" });
dict.Add("wordpad", new string[] { "WordPadClass", "RICHEDIT50W" });
dict.Add("winword", new string[] { "OpusApp", "_WwB" });
dict.Add("excel", new string[] { "XLMAIN", "" });
}


Import file .dll trong System


[DllImport("User32.dll", CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true)]
private static extern Int32 SendMessageW(
IntPtr hWnd,
int Msg,
int wParam,
StringBuilder lParam);
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(
string lpClassName,
string lpWindowName);

[DllImport("User32.dll")]
private static extern IntPtr FindWindowEx(
IntPtr hwndParent,
IntPtr hwndChildAfter,
string lpszClass,
string lpszWindows);


Hàm xử lý sự kiện nút Go để chạy.


private void m_GoBtn_Click(object sender, EventArgs e)
{
string programName = m_ProgramNameTxt.Text;
if (!string.IsNullOrEmpty(programName))
{
Process[] processes = Process.GetProcessesByName(programName);
StringBuilder sbResults = new StringBuilder();
foreach (Process process in processes)
{
// getting the text
IntPtr hWnd = process.Handle;
string windowTitle = process.MainWindowTitle;

// require each file has the different title
hWnd = FindWindow(dict[programName][0], windowTitle);
if (!hWnd.Equals(IntPtr.Zero))
{
// retrieve Edit window handle of Notepad
IntPtr edithWnd = FindWindowEx(hWnd, IntPtr.Zero, dict[programName][1], null);
if (!edithWnd.Equals(IntPtr.Zero))
{
// send WM_SETTEXT message with "Hello World!"
//SendMessage(edithWnd, WM_SETTEXT, 0, new StringBuilder("Hello World!"));

int length = SendMessageW(edithWnd, WM_GETTEXTLENGTH, 0, null);
if (length > 0)
{
StringBuilder sb = new StringBuilder(length);
SendMessageW(edithWnd, WM_GETTEXT, sb.Capacity + 1, sb);
sbResults.AppendLine(sb.ToString());
}
}
}
else
{
MessageBox.Show("Can't recognize the program");
}
}
m_ResultTxt.Text = sbResults.ToString();
}
}


Địa chỉ download SourceCode:

http://cid-e98f889e083fef72.office.live.com/self.aspx/.Public/SourceCode/DataGrabber.zip