I'm writing an utility (http://reg2run.sf.net) which in case execution without arguments works as windows application (shows OpenFileDialog, etc), otherwise - as console application.
So, in first case I don't want to show a console window, that's why project is Windows Application.
But in second - I need to show it, and it's created with
if (ptrNew == IntPtr.Zero)
{
ptrNew = GetStdHandle(-11);
}
if (!AllocConsole())
{
throw new ExternalCallException("AllocConsole");
}
ptrNew = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
if (!SetStdHandle(-11, ptrNew))
{
throw new ExternalCallException("SetStdHandle");
}
StreamWriter newOut = new StreamWriter(Console.OpenStandardOutput());
newOut.AutoFlush = true;
Console.SetOut(newOut);
Console.SetError(newOut);
And what I want - is to grab parent process standard output and use it, if it exists (in case execution via cmd.exe or Far Manager). How can I do it?
I tried
static Process GetParentProc()
{
int pidParent = 0;
int pidCurrent = Process.GetCurrentProcess().Id;
IntPtr hSnapshot = CreateToolhelp32Snapshot(2, 0);
if (hSnapshot == IntPtr.Zero)
{
return null;
}
PROCESSENTRY32 oProcInfo = new PROCESSENTRY32();
oProcInfo.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32));
if (!Process32First(hSnapshot, ref oProcInfo))
{
return null;
}
do
{
if (pidCurrent == oProcInfo.th32ProcessID)
{
pidParent = (int)oProcInfo.th32ParentProcessID;
}
}
while (pidParent == 0 && Process32Next(hSnapshot, ref oProcInfo));
if (pidParent > 0)
{
return Process.GetProcessById(pidParent);
}
else
{
return null;
}
and
StreamWriter newOut = GetParentProc().StandardInput;
but got InvalidOperationException: StandardIn has not been redirected. Because of
GetParentProc().StartInfo.RedirectStandardOutput = false
There are several approaches for applications that need to choose whether to act as console or GUI applications, depending on context, on Windows:
Have two separate applications, and have one conditionally start the other.
A variant of the above strategy, have two applications, one called 'app.com' (i.e. just rename a console EXE with COM extension) and the other called 'app.exe', so that command-line invocations will find app.com first. Because of ancient DOS compatibility, .COM executables are found before .EXEs. (This in configurable in Windows; see the PATHEXT environment variable.)
The rxvt/Cygwin technique, which is one I haven't really seen documented anywhere else.
Let me go into a little bit of detail about how rxvt on Cygwin works. Rxvt is a terminal emulator that normally runs on the X Window system. Because of the limitations of the Win32 console, Cygwin packages it as a more fully-featured console, with support for things like lots of lines of history, dynamic resizing, per-instance configurable fonts and colour themes, non-application-freezing mouse select and copy, etc. In order to run natively on Windows, rxvt shipped with Cygwin includes a tiny X11 wrapper library for Win32. Rxvt on Windows is actually a console application for compatibility reasons with existing native Win32 executables, but most of the time you never see the console; you just see the rxvt terminal emulator window itself.
The way it works is specifically implemented in rxvt/W11/wrap/wrap.c in the rxvt source tree, in the function called hideConsole(). Basically, it opens up its console (with a CreateFile("CONOUT$" ...)), and checks to see if the cursor position is at (0,0) (using GetConsoleScreenBufferInfo() on the console handle).
If it is, then it infers that it has been started as a standalone application, rather than from a console parent application, and thus it knows the OS has created a dedicated Win32 console for the process. It proceeds to hide this console window, but it has to find it first. It uses SetConsoleTitle to set the console window's caption to a unique value based on the name of the application and the current thread ID. It then uses FindWindow to find this window's handle (periodically Sleeping for a few ms if necessary for the title to change, because the console windows are actually controlled by a different process entirely in Windows). When it eventually finds the window handle, it hides it with ShowWindowAsync, passing in SW_HIDE.
Using this approach, you can write an application that:
if started from a console parent, it can continue to use this console
if started as an application, it can optionally choose whether or not to hide the console
The only downside is a very brief flash of a console window at application startup.
You can always the following P/Invoke method:
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
const int ATTACH_PARENT_PROCESS = -1;
Related
We have a desktop Windows app (written in WFP/C#) that we distribute as a single .exe file with no installer (it bundles all its dependencies via a Fody/Costura plugin).
We would like to integrate a local Action Center toast functionality where the app can display a toast and respond to it when it's clicked.
Displaying the toast is straightforward and can be done by using the Microsoft.Toolkit.Uwp.Notifications nuget package. However, in order to actually receive proper notifications when the toast is clicked in the Action Center (as opposed to the balloon tip) we need to register with notification platform.
The guide on how to do this seems to be focused on apps with an installer (e.g. Wix): https://learn.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/send-local-toast-desktop?fbclid=IwAR2AoHRKI88VNGRG-pTUytwhkMuovWT4bEr0RoXEayWpWsoGlghtZeq4Mo4#step-4-register-with-notification-platform
The specific task we're trying to achieve is, from the documentation:
If you're using classic Win32 (or if you support both), you have to declare your Application User Model ID (AUMID) and toast activator CLSID (the GUID from step #3) on your app's shortcut in Start.
How can we do it without writing an installer? We would like our app to do this registration on first run.
Note: the app already has provisions for elevating itself through UAC if needed by restarting itself in Administrator context.
Additional references: WPF native windows 10 toasts
[Update]
I managed to follow the instructions in https://learn.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/send-local-toast-desktop
and https://learn.microsoft.com/en-us/windows/win32/shell/enable-desktop-toast-with-appusermodelid to put together what should have been a working solution, but in the end, clicking on toasts in the Action Center does not trigger OnActivated() in my NotificationActivatior.
Salient points:
Sending notification
var toast = new ToastNotification(toastXml);
DesktopNotificationManagerCompat.CreateToastNotifier().Show(toast);
Registration:
string shortcutPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Programs),
"Toasty.lnk");
DesktopNotificationManagerCompat.RegisterAumidAndComServer
<MyNotificationActivator>(AppName);
DesktopNotificationManagerCompat.RegisterActivator
<MyNotificationActivator>();
if (!File.Exists(shortcutPath))
{
ShortcutManager.RegisterAppForNotifications(
shortcutPath,
Assembly.GetExecutingAssembly().Location,
null,
AppName,
ActivationId);
}
Creating a shortcut
public static void RegisterAppForNotifications(
string shortcutPath,
string appExecutablePath,
string arguments,
string appName,
string activatorId)
{
var shellLinkClass = new ShellLinkCoClass();
IShellLinkW shellLink = (IShellLinkW)shellLinkClass;
shellLink.SetPath(appExecutablePath);
IPropertyStore propertyStore = (IPropertyStore)shellLinkClass;
IPersistFile persistFile = (IPersistFile)shellLinkClass;
if (arguments != null)
{
shellLink.SetArguments(arguments);
}
// https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-id
propertyStore.SetValue(
new PropertyKey("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3", 5),
new PROPVARIANT(appName));
// https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-toastactivatorclsid
propertyStore.SetValue(
new PropertyKey("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3", 26),
new PROPVARIANT(new Guid(activatorId)));
propertyStore.Commit();
persistFile.Save(shortcutPath, true);
}
[Update]
Finally got it to work - not sure what was wrong before, but the final version seems to be okay. Full code: https://gist.github.com/davidair/c4ea207bf6eece4ef08b97ab29a3036f
I have the same problem with my project now.
Managed to find this repository - https://github.com/felixrieseberg/electron-windows-interactive-notifications
Here's C++ implementation for installing shortcut (InteractiveNotifications file, InstallShortcut method). I guess the problem is how we set the value to PropertyStore, string GUID is not suitable for some reason. Still, I wasn't able to solve the problem for now.
UPDATED: Finally, was able to install shortcut from code! Check my example at Github. https://github.com/romayavorskyi/WpfNotificationTest (still a lot of hardcode, but it should give you the general idea). And you were right, shortcut path matters. It seems shortcut should be in the ProgramData folder for correct work.
I have a UWP app that does the recording and calling functionality. For this I have added two FullTrust Apps using Desktop bridge application. When I call just one fullTrust app everything works perfectly, but when I call two FullTrust apps by passing parameters (of the FullTrust apps to be started) the the first app that was started behaves incorrectly. For these two FullTrust apps I have used two different Appservice names declared in the Package.Manifest file of the Windows Packaging Project.
I have noticed that whenever I switch the position of the Fulltrust app call the last application that is called always remains active(has the priority of the Appservice connection) even if both has different app service names.
Here is the code I have added when user opens a page in UWP that starts Win32 app and background App
if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0))
{
await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("Win32");
}
if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0))
{
await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("Background");
}
In the above code, the first app that is Started calls my Win32.exe and second background.exe.
How can I call these two apps independently? whenever we want to start them and close whenever required or may be in future I would like to start two apps at the same time but also I may need to close any app whenever required. Can anyone tel me how can I handle the correct communication path when calling two fullTrust apps at the same time?
How can I call these two apps independently?
For launching multiple desktop app, we suggest to make Launcher app to manage multiple apps, then call LaunchFullTrustProcessForCurrentAppAsync(string parameterGroupId) and pass GroupId parameter. And at first we need add the group in the desktop bridge appxmanifes file.
<Extensions>
<desktop:Extension Category="windows.fullTrustProcess" Executable="Launcher\Launcher.exe">
<desktop:FullTrustProcess>
<desktop:ParameterGroup GroupId="Background" Parameters="/background" />
<desktop:ParameterGroup GroupId="Win32" Parameters="/win32" />
</desktop:FullTrustProcess>
</desktop:Extension>
</Extensions>
Then use the Launcher to start all apps with parameter
static void Main(string[] args)
{
// determine the package root, based on own location
string result = Assembly.GetExecutingAssembly().Location;
int index = result.LastIndexOf("\\");
string rootPath = $"{result.Substring(0, index)}\\..\\";
// process object to keep track of your child process
Process newProcess = null;
if (args.Length > 2)
{
// launch process based on parameter
switch (args[2])
{
case "/background":
newProcess = Process.Start(rootPath + #"FullTrust_Background\FullTrust_Background.exe");
break;
case "/win32":
newProcess = Process.Start(rootPath + #"FullTrust_Win32\FullTrust_Win32.exe");
break;
}
}
}
For more detail please refer this tutorial.
I have a windows form application written in C# that allows me to point to a folder of images and parse those images into a easily view able format for a user. This is a stand alone application and it works fine. I want to extend this application so that instead of it parsing a folder of images, I can hand it a prebuilt data set, with all of the images and meta data preset by an external application via an API.
I have been able to compile the application into a class library and access the classes and structs to actually build the data set without issue, the problem I am having now is launching the application externally with the data set I have built.
For context, I am writing a tool that will allow the user to call this windows form application from Spotfire. Inside of spotfire I am parsing a DataTable object and building the data set from the information I have. Once this data set is built I need to be able to launch the application as a stand-alone process instead of calling the forms explicitly inside of Spotfire. (This is due to a limitation of GUI threads in Spotfire and we can't call a multi threaded process in a single threaded application as well as we want to keep the Spotfire GUI responsive which can't be done if we call the forms directly)
I know I can launch the exe standalone using Process.Start(), however this doesn't let me pass my information to teh application. How can I build this application to allow me to pass information to it? I've been trying to google examples of how to do this and keep coming up empty handed as people will reference ASP.net or things that are over my head.
Thank you in advance!
EDIT: An example of an application that handles this really well is below. We use DPlot Jr to create graphs externally. The dplot.dll exposes the following function:
[System.Runtime.InteropServices.DllImport("dplotlib64.dll")]
public static extern int DPlot_Plot8(
ref DPLOT d, double[] x, double[] y, string cmds);
which I can then use in my code
docNum = dplot.DPlot_Plot8(ref dPlot, X, Y, cmds);
docNums.Add(docNum);
calling this function in this way actually launches the dplot application and passes the object I've built "dPlot" along with the X and Y data in order to plot the information. I would like to build something like this in my windows form application in order to be able to launch it easily from an external application. Unfortunately I don't know how this function works inside the .dll
EDIT2: I have been able to modify the runtime via the commandline as suggested by Aybe. In my desktop application I have created a conditonal in the main program like so.
if (args.Length == 0 && false)
{
Application.Run(new frmWaveFormViewer());
}
else
{
DataSet dataSet = new DataSet();
//dataSet.LoadMetaData(args[0]);
dataSet.LoadMetaData(#"C:\Users\a0273881\AppData\Local\Temp\tmp1141.tmp");
Application.Run(new frmWaveFormViewer(dataSet));
}
the user can then call the forms externally by using the following...
DataSet dataSet = new DataSet(dpList);
dataSet.PrintDatasetMetadataToFile(String.Format(#"C:\Spotfire\DataSetTesting_{0}.csv", DateTime.Now.ToString("yyyyMMdd_HHmmss")));
string args = dataSet.GetMetaData();
ProcessStartInfo starter = new ProcessStartInfo();
starter.FileName = #"C:\Users\a0273881\Desktop\WaveFormViewer.exe";
starter.Arguments = args;
Process.Start(starter);
However, this is not easy to use for other developers.
I am starting to look into WCF, can anyone provide good resources on WCF for dummies? I'm currently reading through: http://www.codemag.com/article/0705041
I have been able to spawn a NamedPipeServer on the application when it is launched. The named pipeserver names itself tagged with the name of the application + the process id that it spawns with. The process number is logged to a ini file in the users appdata folder. The process can be started with an optional command line argument to effect the value of the "callingApplication" which is the INI Header. This way, we can create multiple instances of the application from different callers without interfering and ensuring connection to the correct named pipe.
static void Main(string[] args)
{
string callingApplication = "None";
if (args.Length != 0)
{
callingApplication = args[0];
}
int pId = Process.GetCurrentProcess().Id;
PipeServer.StartPipeServer(pId, callingApplication);
// do things
PipeServer.StopPipeServer();
}
The PipeClient side is accessed through public functions available in a API static class. Functions that connect through the pipe are all housed in a seperate PipeClient class. These functions require a spawned process id in order to connect to the correct pipe. These are api functions to either launch or return the needed pipe from an api
public static class API
{
public static int SendCommand(int aKey, ...)
{
try
{
PipeClient.StartCommandSendClient(input, aKey);
}
catch (TimeoutException)
{
// returns error codes based on exceptions
}
return 0;
}
}
So with this I've managed to create a link between two applications. All that is really required past this is custom implementation of methods exposed through the API class which have custom client methods to call as well. All of this together is pretty simple to call from my calling app...
int aKey = API.GetKey("callingAppName");
API.SendCommand(aKey, "[Reset()][AddPoint(arg1, arg2, arg3)]");
I'm working on a portion of an application that has a 'finder' tool that allows the user to drag and drop a finder onto an application or internet explorer web browser so that our program can locate it and do what it needs to do. This portion of the application was not under any active development for the last few years (last time I believe IE 7 was the latest browser), but it has worked for IE 9 and below. Starting at IE 10 we get problems, and I specifically am using IE 11.
The following code locates the different Internet explorer windows (including tabs) and file explorer windows. We made a quick VB script for extra testing -
dim objShell
dim objShellWindows
set objShell = CreateObject("shell.application")
set objShellWindows = objShell.Windows
if (not objShellWindows is nothing) then
WScript.Echo objShellWindows.Count
for each win in objShellWindows
wscript.Echo TypeName(win)
WScript.Echo win.LocationUrl
WScript.Echo win.LocationName
WScript.Echo win.HWND
next
end if
set objShellWindows = nothing
set objShell = nothing
The above code will execute without error, and it gives the URL and title bar name of all the tabs we have open.
Below is our C# code. It attempts to get the main IE window (not the tab). this.Handle is the handle of this main IE window that the finder tool gets when the user drops it. We're attempting to iterate through the open windows and find the Internet Explorer window that the user selected. This particular snippet is changed slightly from our original implementation, but the end result is the same. As soon as it hits test = window.Item(i) it throws a UnauthorizedAccessException.
ShellWindows windows = null;
IWebBrowser2 shellWindow = null;
IHTMLDocument2 actualDoc = null;
Type shellApplicationType = Type.GetTypeFromProgID("Shell.Application");
Shell32.Shell shellInterface = (Shell32.Shell)Activator.CreateInstance(shellApplicationType);
windows = (ShellWindows)shellInterface.Windows();
bool found = false;
for (int i = 0; i < windows.Count; i++)
{
try
{
object test;
try
{
test = windows.Item(i); //Exception here
shellWindow = (IWebBrowser2)test;
}
catch
{
}
if (shellWindow != null && (IntPtr)shellWindow.HWND == this.Handle)
{
//the rest of the code gets the correct tab from the main IE window
This is the original unedited code from when we first revisited this portion of the program.
ShellWindows windows = null;
IWebBrowser2 shellWindow =null;
IHTMLDocument2 actualDoc = null;
windows = new SHDocVw.ShellWindowsClass();
bool found = false;
for (int i = 0; i < windows.Count; i++)
{
try{
shellWindow = windows.Item(i) as SHDocVw.IWebBrowser2; //Exception here
if (shellWindow != null && (IntPtr)shellWindow.HWND == this.Handle)
{
I would also like to note that instead of a for loop I have tried a foreach loop that followed this syntax
foreach(IWebBrowser2 browser in windows)
and
foreach(InternetExplorer browser in windows)
In those instances, the loop skips over the IE window.
I have looked at IE's security settings. I have disabled Enhanced Protection Mode and allowed cross domain. There does not seem to be a lot of information on this issue, and every approach we try seems to always end up with an UnauthorizedAccessException.
Edit: In response to Hans answer, I do not have any anti malware running on this machine. It is a virtual machine with windows 7 that has the latest SP and updates (no microsoft security essentials). I tried running the app on a 32 bit machine with similar settings and it also failed. After testing it on IE 11, I uninstalled IE 11, rebooted, tried IE 10 (it failed, same error), uninstalled IE 10, rebooted, tried IE 9, and it worked without making any other changes to the system.
Here is the SSCCE as requested by Hans. This code actually works on my target machine. I will return to this post in the next day or two while I handle other tasks that require my attention.
I build this as a 32 bit console app, and ran it on a 64bit machine.
using System;
using SHDocVw;
using mshtml;
namespace GetBrowserSSCCE
{
class Program
{
static void Main(string[] args)
{
ShellWindows windows = null;
IWebBrowser2 shellWindow = null;
windows = new SHDocVw.ShellWindowsClass();
for (int i = 0; i < windows.Count; i++)
{
try
{
shellWindow = windows.Item(i) as SHDocVw.IWebBrowser2;
Console.WriteLine(string.Format("Window Found. HWND: {0}\nName: {1}", shellWindow.HWND, shellWindow.Name));
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("UnauthorizedAccessException caught. Exception Text: " +ex.Message);
}
}
Console.ReadLine();
}
}
}
That this fails in your C# program but not when you run it from the VBScript interpreter points strongly to an environmental problem. Both use the exact same shell interface. The specific exception (underlying error code is 0x8007005) has been reported before on the interwebs but never diagnosed.
First thing you should focus on whenever you have an environmental problem, particularly the kind associated with access rights, is the anti-malware installed on the machine. Disable it and try again.
Second one you should focus on is a quirk associated with ShellWindows, it doesn't just enumerate Internet Explorer windows but also Windows Explorer windows. You've been looking at having sufficient access to IE but that isn't enough, this code can also fail if you happen to have an Explorer window opened and there's an access problem with the explorer.exe process. Do note that your Activator.CreateInstance() method call is not equivalent to the VBScript code, Activator.GetObject() is. So your changes would actually make the problem worse if this is underlying problem.
Third detail that's worth checking is the bitness of your process. By default, your VBScript code will run in the 64-bit script interpreter on a machine that boots the 64-bit version of Windows. But the default setting for a C# project is to run in 32-bit mode. Right-click your EXE project, Properties, Build tab and tinker with the Platform target setting, the 'Prefer 32-bit' checkbox if you see it. This is not an explanation for the error code, it can however affect the effectiveness of anti-malware to intrude.
I am trapping for the execution of some old 16-bit applications that our internal folks should no longer be using. They are 1985 DOS apps, so trapping for them was easy... capture any process that launches under NTVDM.exe
Now, the problem is finding out which program NTVDM is actually running under the hood. Apparently there are a coupleof the 1985 programs that they SHOULD be allowed to run, so I need to see the actual EXE name that is hiding under NTVDM.
WqlEventQuery query =
new WqlEventQuery("__InstanceCreationEvent",
new TimeSpan(0, 0, 1),
"TargetInstance isa \"Win32_Process\"");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Start();
...
static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
ProcessInfo PI = new ProcessInfo();
PI.ProcessID = int.Parse(instance["ProcessID"].ToString());
PI.ProcessName = instance["Name"].ToString();
PI.ProcessPath = instance["ExecutablePath"].ToString();
// Here's the part I need...
PI.ActualEXE = ???;
// ... do the magic on the PI class ...
instance.Dispose();
}
When I capture the instance information, I can get the command line, but the arguments are "-f -i10" ... There is no EXE name on the command line. Is there any other method/property I should be looking at to determine the EXE name of the 16-bit application that's actually running?
UPDATE: Let me refine the question: If I can find the NTVDM process, how can I -- programatically -- know the actual path to the EXE that is being executed underneath?
Thanks.
The trick is not to use VDMEnumProcessWOW (which gives the VDMs), but to use VDMEnumTasksWOW. The enumerator function that you pass to this function will be called for each 16 bit task in the specified VDM.
I haven't checked it myself, but according to the documentation, this library of CodeProject does exactly that, if you pass in the PROC16 enum value. It's C++, if you need help compiling that code and calling it from C#, let me know and I'll give you an example.
A program that uses this technique is Process Master, it comes with full source. I suggest you run it to find out whether it gives the info you need, and if so, you can apply this method to your own application (it doesn't run on Windows Vista or 7, it uses old VB5 code, apparently it's not compatible. It should run on XP).
If things with these functions do not go as planned, you may be on Vista and may need the hotfix described in this StackOverflow question, which points to downloading a hotfix, which is in turn described here:
"An application that uses the
VDMEnumProcessWOW function to
enumerate virtual DOS machines returns
no output or incorrect output on a
computer that is running a 32-bit
version of Windows Vista"
Update: while this seems promising, I applied the patch, ran several versions of the code, including Microsoft's, and while they all work on XP, they fail silently (no error, or wrong return value) on Vista.
The "kinda" working code
Update: I experimented with (amongst others) with the following code, which compiles fine in C# (and can be written simpler, but I didn't want to run a marshal-mistake risk). When you add these functions, you can call Enum16BitProcesses, which will write the filenames of the EXE files of the 16 bit processes to the Console.
I can't run it on Vista 32 bit. But perhaps others can try and compile it, or find the error in the code. It would be nice to know whether it works on other systems:
public class YourEnumerateClass
{
public static void Enum16BitProcesses()
{
// create a delegate for the callback function
ProcessTasksExDelegate procTasksDlgt =
new ProcessTasksExDelegate(YourEnumerateClass.ProcessTasksEx);
// this part is the easy way of getting NTVDM procs
foreach (var ntvdm in Process.GetProcessesByName("ntvdm"))
{
Console.WriteLine("ntvdm id = {0}", ntvdm.Id);
int apiRet = VDMEnumTaskWOWEx(ntvdm.Id, procTasksDlgt, IntPtr.Zero);
Console.WriteLine("EnumTaskWOW returns {0}", apiRet);
}
}
// declaration of API function callback
public delegate bool ProcessTasksExDelegate(
int ThreadId,
IntPtr hMod16,
IntPtr hTask16,
IntPtr ptrModName,
IntPtr ptrFileName,
IntPtr UserDefined
);
// the actual function that fails on Vista so far
[DllImport("VdmDbg.dll", SetLastError = false, CharSet = CharSet.Auto)]
public static extern int VDMEnumTaskWOWEx(
int processId,
ProcessTasksExDelegate TaskEnumProc,
IntPtr lparam);
// the actual callback function, on Vista never gets called
public static bool ProcessTasksEx(
int ThreadId,
IntPtr hMod16,
IntPtr hTask16,
IntPtr ptrModName,
IntPtr ptrFileName,
IntPtr UserDefined
)
{
// using PtrToStringAnsi, based on Matt's comment, if it fails, try PtrToStringAuto
string filename = Marshal.PtrToStringAnsi(ptrFileName);
Console.WriteLine("Filename of WOW16 process: {0}", filename);
return false; // false continues enumeration
}
}
Update: Intriguing read by the renown Matt Pietrek. Mind the sentence, somewhere near the end:
"For starters, MS-DOS-based programs
seem to always run in separate NTVDM
sessions. I was never able to get an
MS-DOS-based program to run in the
same session as a 16-bit Windows-based
program. Nor was I able to get two
independently started MS-DOS-based
programs to run in the same NTVDM
session. In fact, NTVDM sessions
running MS-DOS programs don't show up
in VDMEnumProcessWOW enumerations."
Seems that, to find out what processes are loaded, you'll need to write a hook into NTVDM or write a listener that monitors access to the file. When the application that tries to read a certain DOS file is NTVDM.exe, it's bingo. You may want to write a DLL that's only attached to NTVDM.exe, but now we're getting a bit ahead of ourselves. Long story short: this little ride into NTVDM has shown "possibilities" that appeared real hoaxes in the end.
There's one other way, but time is too short to create an example. You can poke around in the DOS memory segments and the EXE is usually loaded at the same segment. But I'm unsure if that eventually will lead to the same result and whether it's worth the effort.
This works for me:
Follow the instructions at Description of the Software Restriction Policies in Windows XP to open the local or domain policy editor.
Under Software Restriction Policies -> Additional Rules, right click and select New Hash Rule.
Browse to (for example) edit.com. Make sure Security Level is set to Disallowed. Click OK.
Now,
C:\>edit
The system cannot execute the specified program.
(I get the same results from command.com and cmd.exe -- under Win XP)
From this link about VDMDBG functions, you may be able to P/Invoke "VDMEnumProcessWOW()", then enumerate modules within the process using PSAPI.
Note Regarding 16-bit DOS Applications:
None of the VDMDBG functions work with
16-bit DOS applications. To enumerate
DOS VDMs, you need to use another
method. First, you could use
VDMEnumProcessWOW() to make a list of
all Win16 VDMs, and then enumerate all
instances of NTVDM.exe using some
other scheme (such as PSAPI). Any
NTVDM.exe from the full enumeration
that was not in the Win16 list is a
DOS VDM. You can create and terminate
16-bit DOS applications with
CreateProcess() and
TerminateProcess().
Hope that helps...