I have a hotkey window application in C# and I want all the text from the focused window of other application on pressing hotkey like notepad, browser, command window(cmd), Turbo c++, Pascal etc.
So Is it possible?
If any one have idea please help me with code example.
I have attach screen shot. I want to read text from this window. On pressing hotkey I want to read text "This is my test text".
There is a GetWindowText() in user32 API,
but if you need to get text from a control in another process, GetWindowText() won't work.
You have to use SendMessage() with WM_GETTEXT instead:
const UInt32 WM_GETTEXT = 0x000D;
const UInt32 WM_GETTEXTLENGTH = 0x000E;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, StringBuilder lParam);
static string GetWindowTextRaw(IntPtr hwnd)
{
// Allocate string length
int length = (int)SendMessage(hwnd, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
StringBuilder sb = new StringBuilder(length + 1);
// Get window text
SendMessage(hwnd, WM_GETTEXT, (IntPtr)sb.Capacity, sb);
return sb.ToString();
}
Application that call themselves "Screen Reader" (for visually impaired people) do that kind of things, sort of.
They use the old MSSA (Microsoft Active Accessibility) APIs and/or the new UIAutomation APIs.
With the two APIs, if you have a "Main Window" HWND, you can then browse the tree of the componants making the app. You can then retrieve properties, such as "Text" or "Name" and so on.
If the application doesn't support Accessive technologies, you fall back on case by case solutions, which means eventually awful hacks (as APIs hooking) or more regular methods (as DLL injection and use of the JNI Invocation API in the JAVA case).
Its is not directly possible through C#,
Still microsoft provides with WMI services which can utilized to get at max information on the machine and processes. Kindly check MSDN
You can download WMI tool from here and possible check Win32 classes and methods, you may find useful information for your requirement
Related
I have a project where I need to load a Postscript font from disk.
I found I could use "AddFontFile". Doing some research I see that I have to pipe the two fonts http://msdn.microsoft.com/en-us/library/system.drawing.text.privatefontcollection.addfontfile.aspx together so I tried:
fontCollection = new PrivateFontCollection();
fontCollection.AddFontFile(#"C:\Temp\Font\myfont.PFM|C:\Temp\Font\myfont.PFB");
I'm getting a a error "Illegal characters in path".
I'm not sure if I'm piping the two fonts correctly.
Any help would be great, I should mention we are still on XP not sure if that makes a differnts or not.
Mike
You cannot have the pipe | character in your filename. PrivateFontCollection.AddFontFile requires a valid filepath. Hence your "Illegal characters in path" exception. The input at MSDN is A String that contains the file name of the font to add. Try passing a single file at a time - I don't know about this piping idea..
As for your Postscript desire, the Remarks section states that OpenTypes have limited support.
After some searching I got it to work and I'd like to share on how I solved the this:
AddFontFile was the wrong API i Needed to use AddFontResource instead
String fontPath = #"C:\Temp\Font2\GXSTRA03.PFM|C:\Temp\Font2\GXSTRA03.PFB";
int result = AddFontResource(fontPath);
long msg = SendMessage(HWND_BROADCAST, WM_FONTCHANGE, IntPtr.Zero, IntPtr.Zero);
to remove the font resource
RemoveFontResource(#"C:\Temp\Font2\GXSTRA03.PFM|C:\Temp\Font2\GXSTRA03.PFB");
long msg = SendMessage(HWND_BROADCAST, WM_FONTCHANGE, IntPtr.Zero, IntPtr.Zero);
If anyone is new on making a external WinApi call here is the import and import DLL code that I used
using System.Runtime.InteropServices;
private static uint WM_FONTCHANGE = 0x1D;
Import("gdi32.dll")]
static extern int AddFontResource(string lpFilename);
[DllImport("gdi32.dll")]
static extern bool RemoveFontResource(string lpFileName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
This fonts now shows in word and notepad ect..
I would like to have a function to refresh the desktop like pressing "F5" does. I found many codes with Sendmessage and ToggleDesktopIcons on/off but none worked for me like manual hit of "F5" does. I saw also some topics here, but all with non-working solutions for this matter.
I am on Windows 7 64 Bit with IE 10 and use C# Net Framework 2.
I found also this code, but C# doesn't accept it, even if it seems to me as the right function.
I dunno what I need to change here. I would expect that the IDE would tell me what is my mistake here or what I need to correct. Can someone please correct me this function or suggest another function which is compatible to C#.
procedure RefreshDesktop2;
var
hDesktop: HWND;
begin
hDesktop := FindWindowEx(FindWindowEx(FindWindow('Progman', 'Program Manager'), 0,
'SHELLDLL_DefView', ''), 0, 'SysListView32', '');
PostMessage(hDesktop, WM_KEYDOWN, VK_F5, 0);
PostMessage(hDesktop, WM_KEYUP, VK_F5, 1 shl 31);
end;
Question:
How do I make the code above working in C# (translate in C#) or how looks a similar code in C# like.
Refreshing the desktop with its icons/settings like by pressing "F5" on a selected desktop icon is my goal. Several codes which I tried in similar questions brought me no result.
OK, I don't really understand your code, in fact you have to find the exact window to send the F5 keypress to it so that it will refresh the desktop. Here is the c# code (tested and worked like a charm:)
[DllImport("user32")]
private static extern int PostMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32")]
private static extern IntPtr FindWindow(string className, string caption);
[DllImport("user32")]
private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr startChild, string className, string caption);
public void RefreshDesktop(){
IntPtr d = FindWindow("Progman", "Program Manager");
d = FindWindowEx(d, IntPtr.Zero, "SHELLDLL_DefView", null);
d = FindWindowEx(d, IntPtr.Zero, "SysListView32", null);
PostMessage(d, 0x100, new IntPtr(0x74), IntPtr.Zero);//WM_KEYDOWN = 0x100 VK_F5 = 0x74
PostMessage(d, 0x101, new IntPtr(0x74), new IntPtr(1 << 31));//WM_KEYUP = 0x101
}
However I think there are still other choices for you to refresh the desktop programmatically, here is one of the links How to refresh the windows desktop programmatically (i.e. F5) from C#?
This old stackoverflow post is asking pretty much the same question that I have, however using Spy++ I have obtained the controls handle ID. Now what? :)
I am not sure what this process is called where I can obtain the contents of another applications control from a .net application, therefore I am not having much success with results on the old google machine.
I have an MFC application with a listbox that contains data I need to automate a task using a WPF C# application. I would prefer not to use an external lib and don't think it would be too labour intensive once I have found the process and have my C# app take visibility of the respective list control to do what I need.
Can anyone please point me in the right direction as to what I should be looking up or provide some code to get me started. At this point I'm stuck and my little project relies pretty heavily on this. I don't want to use an OCR either.
Thanks,
Ash
To get text from Win32 ListBox control you have to use messages and functions specially for that control, here is a reference :
http://msdn.microsoft.com/en-us/library/windows/desktop/ff485971%28v=vs.85%29.aspx
In your case you should first see how many items are in the listbox with LB_GETCOUNT, and then for each item get text with LB_GETTEXT.
Here is the method that will return items in a list, parameter is ListBox control window handle :
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, StringBuilder lParam);
const int LB_GETCOUNT = 0x018B;
const int LB_GETTEXT = 0x0189;
private List<string> GetListBoxContents(IntPtr listBoxHwnd)
{
int cnt = (int)SendMessage(listBoxHwnd, LB_GETCOUNT, IntPtr.Zero, null);
List<string> listBoxContent = new List<string>();
for (int i = 0; i < cnt; i++)
{
StringBuilder sb = new StringBuilder(256);
IntPtr getText = SendMessage(listBoxHwnd, LB_GETTEXT, (IntPtr)i, sb);
listBoxContent.Add(sb.ToString());
}
return listBoxContent;
}
This question's answer should get you started. Google P/Invoke and FindWindow() / GetWindowText() family of methods.
Hope that helps.
I am developing an application for WINDOWS CE5.0 based device. It requires ORIYA language(INDIAN REGIONAL LANGUAGE) to be used completely. As visual studio use ENGLISH as standard language, please tell me how to proceed? I tried to copy the font in WINDOWS CE device's WINDOWS/FONTS folder but as i restart the device that font file disappears. I developed the application in c# and changed labels text into oriyaa in Development system. It looks fine on the development system but as i deployed it into device, All label text appears in ENGLISH. I dont know whats happening? I also need to set the LABEL.TEXT property in ORIYA language. Is it possible? How to take user input in ORIYA? Please help..... Thanks...
Not very sure as what you meant by browser but for the Forms you can go about using PrivateFontCollection
you can load the font from a folder in your app and then use
AddFontFile or AddMemoryFont as per your need. So now the Client can see the controls in the font you set and its available to it irrespective of its installed or not
I have used the following approach with English-based fonts, but I am not sure if it will work on your case. The original source of this approach is a nice post from Chris Tacke (SO user #ctacke) with some modifications.
[DllImport("coredll.dll")]
private static extern int AddFontResource(string lpszFilename);
[DllImport("coredll.dll", SetLastError = true)]
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
static IntPtr HWND_BROADCAST = (IntPtr)0xFFFF;
const int WM_Fontchange = 0x001D;
private static void RegisterFont(string aFontPath, string aTargetFontPath)
{
IntPtr thir = (IntPtr)0;
IntPtr fourth = (IntPtr)0;
try
{
if (!System.IO.File.Exists(aTargetFontPath))
System.IO.File.Copy(aFontPath, aFontTargetPath);
}
catch { throw; }
int _Loaded = AddFontResource(aFontTargetPath);
if (_Loaded != 0)
SendMessage(HWND_BROADCAST, WM_Fontchange, thir, fourth);
}
I've noticed something very strange. I was trying to call the CRT function "putchar", and was unable to get it to work. So I double-checked that I wasn't missing something, and I copied the code directly from the P/Invoke tutorial on MSDN to see if it worked.
http://msdn.microsoft.com/en-us/library/aa288468%28VS.71%29.aspx
You'll notice that they import "puts".
So I tested the exact code copied from MSDN. It didn't work! So now I got frustrated. I've never had this problem before.
Then I just so happened to run WITHOUT debugging (hit ctrl+f5), and it worked! I tested other functions which output to the console too, and none of them work when debugging but all work when not debugging.
I then wrote a simple C dll which exports a function called "PrintChar(char c)". When I call that function from C#, it works even if I'm debugging or not, without any problems.
What is the deal with this?
The Visual Studio hosting process is capable of redirecting console output to the Output window. How exactly it manages to do this is not documented at all, but it gets in the way here. It intercepts the WriteFile() call that generates the output of puts().
Project + Properties, Debug tab, untick "Enable the Visual Studio hosting process". On that same page, enabling unmanaged debugging also fixes the problem.
It's a bad example, using the C-Runtime Library DLL to call puts. Keep reading the tutorial as there is good info there, but try making Win32 API calls instead.
Here is a better introduction to p/invoke: http://msdn.microsoft.com/en-us/magazine/cc164123.aspx
It's old, but the information is still good.
Edited
My explaination was wrong.
I went looking for a correct explaination and I discovered that the C-Runtime puts method and the .NET Framework Console.Write method differ in how they write to the console (Console.Write works where the p/invoke to puts does not). I thought maybe the answer was in there, so I whipped up this demonstration:
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
class Program
{
public static void Main()
{
int written;
string outputString = "Hello, World!\r\n";
byte[] outputBytes = Encoding.Default.GetBytes(outputString);
//
// This is the way the C-Runtime Library method puts does it
IntPtr conOutHandle = CreateFile("CONOUT$", 0x40000000, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
WriteConsole(conOutHandle, outputBytes, outputString.Length, out written, IntPtr.Zero);
//
// This is the way Console.Write does it
IntPtr stdOutputHandle = GetStdHandle(STD_OUTPUT_HANDLE);
WriteFile(stdOutputHandle, outputBytes, outputBytes.Length, out written, IntPtr.Zero);
// Pause if running under debugger
if (Debugger.IsAttached)
{
Console.Write("Press any key to continue . . . ");
Console.ReadKey();
}
}
const int STD_OUTPUT_HANDLE = -11;
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
static extern int WriteFile(IntPtr handle, [In] byte[] bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, IntPtr securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
static extern bool WriteConsole(IntPtr hConsoleOutput, [In] byte[] lpBuffer, int nNumberOfCharsToWrite, out int lpNumberOfCharsWritten, IntPtr mustBeZero);
}
Both of those successfully output under the debugger, even with the hosting process enabled. So that is a dead end.
I wanted to share it in case it leads someone else to figuring out why it happens -- Hans?