Pregunta

Tan larga historia corta, estoy tratando de automatizar algunas cosas cuando mi computadora se acerca. Pensé que escribiría una aplicación C # Console para hacer esto y luego agregarlo a una tarea de programación en Windows para ejecutar en BOOTUP. Mi problema es con un programa, requiere una contraseña y no tiene opciones para abrirla a través de la línea de comandos. Por lo tanto, debe ser ingresado manualmente. Mi pensamiento fue recuperar mi contraseña de una base de datos de KeetAss y usar para ingresar la contraseña e iniciar sesión en el programa. El problema que estoy teniendo es el tiempo que se necesita para cargar; No tengo forma de detectar cuando la interfaz GUI se ha cargado y está listo para mis envíos. ¿Hay alguna forma de detectar esto? Supongo que todo lo que tengo que trabajar es la clase de "proceso" ya que es lo que solía ejecutar el programa. También tenga en cuenta que cuando ejecuto el ejecutable usando Process.Start (), el programa crea otro proceso para iniciar sesión, pero no tiene una ventana asociada que pueda ver con las llamadas API de Windows.

Está bien, eso fue largo, puedo volver a CAP ...

problema: Desde C # detectando cuando un programa de terceros ha cargado (es decir, la pantalla de inicio se ha ido y la GUI está lista para la interacción del usuario, lo que significa que no solo puedo confiar si el proceso se está ejecutando o no). Además, no hay opciones de línea de comandos para el programa de terceros, o simplemente lo ejecutaría con la contraseña como un argumento.

Objetivo: Para usar envíos para automatizar ingresar una contraseña, pero mi programa debe esperar a que la aplicación de terceros finalice la carga.

Notas: Uso de la aplicación C # .NET 3.5 Consola No detectar la carga para mi propia forma, sino un tercero, de lo contrario, esto sería fácil (I.E. Form_Aled Event ...)

Gracias por mirar mi pregunta, si desea más detalles o cualquier cosa, hágamelo saber.

update :

resuelve problema! Las dos respuestas que recibí combinadas para darme la solución que quería. Entonces, si alguien se llena, esto más tarde, aquí es lo que hice para que funcione.

Por lo tanto, este programa automatiza un inicio de sesión para algún software de cliente en el que debe iniciar sesión. Mi problema era que el software no ofrecía la opción ni la documentación para los PRAMETERS de la línea de comandos que ofrecen muchos otros programas para que pueda iniciar sesión con un archivo de llaves o algo así. Este programa también está deshabilitado. Copia y pegue para que la contraseña debe escribirse manualmente, lo que es un gran dolor si usa contraseñas como yo, largas complicadas sin patrones. Así que escribí este programa para mi beneficio, así que otros en el trabajo; Simplemente lo programe para que se ejecute en el inicio de sesión en mi máquina de Windows y se abre el software del cliente y realiza iniciar sesión automáticamente.

//
// IMPORTANT Windows API imports....
//

[DllImport("user32.dll", SetLastError = true)]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint procId);

[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); 

[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetForegroundWindow(IntPtr hWnd);


// When I get to this point in my code, I already had the password and window title...
string password = "password";
string title = "window title";

// This gets a handle to the window I want where "title" is the text in the title
// bar of the window as a string.
// This is a Windows API function that must be imported by DLLImport
// I had to get the handle this way because all I knew about the third party
// window was the title, not the process name or anything...
IntPtr hWnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, title);

// Now that I have a handle to the login window I used another windows API
// call to get the process ID.

// This windows API call gives me the Process ID as an out parameter and returns
// the thread ID of the window. I don't use the thread it, but maybe you can...
uint loginWindowProcId;
uint loginWindowThreadId = GetWindowThreadProcessId(hWnd, out loginWindowProcId);

// now I can just use .NET to find the Process for me...
Process loginWindowProcess = null;

if (0 != loginWindowProcId)
{
  // get the process object
  loginWindowProcess = Process.GetProcessById((int)loginWindowProcId);

  // This right here is why I wanted the Process structure. It takes a
  // little while for the client software to load and be ready. So here
  // you wait for the window to be idle so you know it has loaded and can
  // receive user input, or in this case keys from "SendKeys".
  loginWindowProcess.WaitForInputIdle();

  // I use yet another windows API call to make sure that the login window
  // is currently in the foreground. This ensures that the keys are sent
  // to the right window. Use the handle that we started with.
  SetForegroundWindow(hWnd);

  // Now send the password to the window. In my case, the user name is 
  // always there from my windows credentials. So normally I would type in the
  // password and press ENTER to login. But here I'll use SendKeys to mimic my
  // behavior.
  SendKeys.SendWait(password);   // send password string
  SendKeys.SendWait("{ENTER}");  // send ENTER key

  // Now the client should be logging in for you! : )

  // IMPORTANT NOTE
  // If you are using a console application like I am, you must add a reference to
  // System.Windows.Forms to your project and put "using System.Windows.Forms;" in
  // your code. This is required to use the "SendKeys" function.
  //
  // Also this code is just for my testing (quick and dirty), you will want to write 
  // more checks and catch errors and such. You should probably give the 
  // WaitForInputIdle a timeout etc...
}

¿Fue útil?

Solución

Puede consultar con el proceso.waitforinputidle después de comenzar un proceso, y espere hasta que esté completamente iniciado, aquí está el ejemplo simple:

http://msdn.microsoft.COM / EN-EEUU / Library / XB73D10T% 28V= vs.71% 29.aspx

Otros consejos

Intente mirar eso: http://www.acoolsip.com/a-cool-blog/science-and-technology/151-c-sending-commands-to-dependent-windows.html

Puede verificar si se muestra la ventana (usando el enlace) y luego envíe mensajes (también en el enlace)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top