我的问题是 PostMessage Windows API 工作不正常,因为它在从控制台应用程序运行时工作。
工作代码:
我有 2 个应用程序 [1] 是控制台应用程序 [2] Windows 窗体应用程序。
要求是我想向所有正在运行的应用程序实例发送消息。
控制台应用程序代码:
class Program
{
#region Dll Imports
public const int HWND_BROADCAST = 0xFFFF;
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32")]
public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
[DllImport("user32")]
public static extern int RegisterWindowMessage(string message);
#endregion Dll Imports
public static readonly int WM_ACTIVATEAPP = RegisterWindowMessage("CLOSE");
static void Main(string[] args)
{
//we tried to create a mutex, but there's already one (createdNew = false - another app created it before)
//so there's another instance of this application running
Process currentProcess = Process.GetCurrentProcess();
//get the process that has the same name as the current one but a different ID
foreach (Process process in Process.GetProcessesByName("ClientApp1"))
{
if (process.Id != currentProcess.Id)
{
IntPtr handle = process.MainWindowHandle;
//if the handle is non-zero then the main window is visible (but maybe somewhere in the background, that's the reason the user started a new instance)
//so just bring the window to front
//if (handle != IntPtr.Zero)
}
}
}
}
上面的代码按预期工作。
我的问题从这里开始。我想从 Windows 服务而不是控制台应用程序运行相同的代码。需要立即指导。
似乎当我从 Windows 服务运行此代码时,它没有掌握进程或服务在不同的帐户中运行,因此没有传递消息。
胡说叔叔
相关分类