이미 실행중인 경우 콘솔 응용 프로그램에 인수를 전달하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/3257311

문제

Windows Mobile의 콘솔 응용 프로그램을 사용하여 들어오는 메시지 차단을 처리합니다.동일한 콘솔 응용 프로그램에서 매개 변수를 기반으로 매개 변수 (String args [])를 허용하고 메시지 인터셉터를 등록하십시오.

Interceptortype은 enum

입니다.
static void Main(string[] args)
        {                 

            if (args[0] == "Location")
            {               

                addInterception(InterceptorType.Location, args[1],args[2]);
            } 

        }


private static void addInterception(InterceptorType type, string Location, string Number )
    {

        if (type == InterceptorType.Location)
        {

           using (MessageInterceptor interceptor = new MessageInterceptor(InterceptionAction.NotifyAndDelete, false))
           {

               interceptor.MessageCondition = new MessageCondition(MessageProperty.Sender, MessagePropertyComparisonType.Contains, Number, false);

               string myAppPath = Assembly.GetExecutingAssembly().GetName().CodeBase;

               interceptor.EnableApplicationLauncher("Location", myAppPath);

               interceptor.MessageReceived += new MessageInterceptorEventHandler(interceptor_MessageReceived);


           }


        }


    }


static void interceptor_MessageReceived(object sender, MessageInterceptorEventArgs e)
    {

        //Do something



    }
.

백그라운드에서 계속 실행되고 들어오는 메시지를 가로 채기 때문에이 콘솔 응용 프로그램을 만들었습니다.

이것은 처음으로 잘 작동합니다.그러나 문제는 addInterception 메소드를 계속 호출하여 후속 차단 규칙을 추가해야한다는 것입니다.이렇게하면 규칙을 추가 할 때마다 콘솔 응용 프로그램이 다시 시작되므로 다시 시작됩니다.이 작업을 한 번만 실행하고 더 많은 메시지 인터셉터 규칙을 추가합니까?

도움이 되었습니까?

해결책

명령 프롬프트를 한 번 호출하기 위해 이미 메소드가 이미 있으므로 논리를 몇 가지 간단한 루핑으로 업데이트하여 n 명령을 전달할 수 있습니다.

편집 : 나는 그것이 내가 말하는 것을 정확히 보여주는 완전히 편리한 예를 썼다.다시 시작하지 않고 하위 프로세스가 여러 번 호출되는 방법에 유의하십시오.이 아이디어가 원하지 않는 것과 정확히있는 X 프로세스로 이어질 것이기 때문에 인수가 전달되는 단순한 명령 줄 실행이 아닙니다.

상위 프로세스 : (system.diagnostics.process가있는 하나의)

/// <summary>
    /// This is the calling application.  The one where u currently have System.Diagnostics.Process
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            System.Diagnostics.Process p = new Process();
            p.StartInfo.CreateNoWindow = false;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.FileName = @"C:\AppfolderThing\ConsoleApplication1.exe";
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;


            p.Start();            
            p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
            {
                Console.WriteLine("Output received from application: {0}", e.Data);
            };
            p.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e)
            {
                Console.WriteLine("Output received from application: {0}", e.Data);
            };
            p.BeginErrorReadLine();
            p.BeginOutputReadLine();
            StreamWriter inputStream = p.StandardInput;
            inputStream.WriteLine(1);
            inputStream.WriteLine(2);
            inputStream.WriteLine(-1);//tell it to exit
            p.WaitForExit();
        }

    }
.

자식 프로세스 :

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    enum InterceptorType
    {
        foo,
        bar,
        zee,
        brah
    } 
    /// <summary>
    /// This is the child process called by System.Diagnostics.Process
    /// </summary>
    class Program
    {
        public static void Main()
        {
            while (true)
            {
                int command = int.Parse(Console.ReadLine());
                if (command == -1)
                    Environment.Exit(0);
                else
                    addInterception((InterceptorType)command, "some location", "0");
            }
        }
        private static void addInterception(InterceptorType type, string Location, string Number)
        {
            switch (type)
            {
                case InterceptorType.foo: Console.WriteLine("bind foo"); break;
                case InterceptorType.bar: Console.WriteLine("bind bar"); break;
                default: Console.WriteLine("default bind zee"); break;
            }

        }


        static void interceptor_MessageReceived(object sender, EventArgs e)
        {
            //Do something  
        }  
    }
}
.

코드 인쇄에는 관리 서비스 라이브러리 .

다른 팁

편집

사람들이 당신의 질문 (또는 나는 오전)을 잘못 정제하는 것 같습니다. 그래서 문제를 어떻게 보는지에 대한 설명이 있습니다.

명령 줄 매개 변수를 취하는 콘솔 앱이 있습니다. 이 매개 변수는 무언가 (실제로 무의미한 것)에 사용됩니다. 앱이 새 명령 줄 ARGS로 앱을 호출하여 앱을 이미 실행 한 후 매개 변수를 추가 할 수 있기를 원합니다.

무슨 일이 일어나는 일은 먼저 TEH 이후에 언제든지 앱을 호출 할 때 기존 실행중인 응용 프로그램으로 이동하는 명령 줄 인수 대신 프로세스의 새 인스턴스가 시작됩니다.

End Edit

해결책은 상당히 간단하며 두 조각이 필요합니다.

  1. 뮤텍스라는 이 필요합니다. 모든 (가난한) 이유로, CF는 이름을 취하는 뮤텍스 버전을 노출시키지 않으므로 p / invoke createmutex r. (SDF와 같이 라이브러리를 사용하십시오). 앱은 시작시 뮤텍스를 만들고 이미 존재하는지 확인해야합니다. 그것이 첫 번째 실행 인스턴스가 아니며 정상적으로 실행됩니다. 뮤텍스가 존재하면 p2p 대기열 그런 다음

  2. 뮤텍스를 확인한 후 첫 번째 인스턴스는 작업자 스레드를 생성합니다. 이 스레드는 메시지에 대한 P2P 대기열에서 수신합니다. 그들이 들어올 때, 당신은 그들을 다루고 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top