Can an application be used to behave like a function?

61 Views Asked by At

I'm a beginner so I'll try to be as clear as I can.I want to know if it is possible to run a custom application and have it return and store a result in a boolean,int or string in another application(the one that calls it) ? Basically I want it to behave like a function that returns a value but to another program that calls it instead. I would like to do it in VB.net. Something like this when it comes to using boolean :

 a = Process.Start("C:\path_to\myapp.exe")
 if (a) then 
    'execute
 end if
2

There are 2 best solutions below

6
David W On

At the simplest level, no, the design of the process mechanism doesn't inherently afford the ability to do what you're suggesting. The closest you could get is for the called process to exit with a particular return value, but that requires use of a particular API (GetExitCodeProcess) - not the return from the Start method you've illustrated here.

You can do such things as capture the output of the new process, which isn't a very robust solution, or create a temporary file that contains a value the "calling" process can read, which is even less robust. The other extreme would be to investigate specific techniques for interprocess communication.

If you could expand a bit on your problem, a more specific set of possible solutions could be offered. If your value of interest is being generated by a library or some shared code, that might afford a much more suitable return mechanism.

0
Drarig29 On

Here's an example of ConsoleApplication :

Imports System.IO

Module Main

    Sub Main()
        Dim Output As Boolean = File.Exists(My.Computer.FileSystem.SpecialDirectories.Desktop & "\file.txt")
        Console.WriteLine(Output)
    End Sub

End Module

And how to read the output (stdout) of the previous console application (this function returns a Boolean) :

Public Function GetOutput(executable As String) As Boolean
    Using p As New Process With {.StartInfo = New ProcessStartInfo With {
            .CreateNoWindow = True,
            .FileName = executable,
            .RedirectStandardOutput = True,
            .WindowStyle = ProcessWindowStyle.Hidden,
            .UseShellExecute = False}}
        p.Start()

        Dim output As String = p.StandardOutput.ReadToEnd()
        p.WaitForExit()
        Return CBool(output.Trim)
    End Using
End Function

You can now do what you wanted to do by using this :

a = GetOutput("C:\path_to\myapp.exe")
If a Then
    'execute
End If

See also (in C#) : How to make a Main Method of a console based application to return a string type.