title: Controlling Matlab instance through C# application
body: <p><strong>Background</strong>  </p>
  
  <p>I have several Matlab scripts that create interactive sessions with the user (kind of like a game), and I want to create a C# GUI as a front-end to kickoff these scripts instead of manually typing in Matlab's command window. The reason for this is these scripts are separated into distinct directories and require several input parameters to set up, many of which are identical if the user is the same.</p>
  
  <p><strong>Problem Description</strong>  </p>
  
  <p>The main question I have is how do I communicate with the Matlab instance? I'm not interested in passing data back and forth; rather, I would like to send 1 command to Matlab and let it do its thing. An example would be:</p>
  
  <pre><code>cd('D:\Script1\'); fnScript1(0, true, 'default') %command for Matlab to execute
  </code></pre>
  
  <p>My planned approach is:</p>
  
  <ol>
  <li>Generate the command on the GUI side and copy to clipboard</li>
  <li>Use SetForegroundWindow() to give focus to Matlab</li>
  <li>Give focus to the command prompt</li>
  <li>Paste the command from the clipboard using SendKeys.Send("^v")</li>
  <li>Execute the command using SendKeys.Send("{ENTER}")  </li>
  </ol>
  
  <p>The big problem I have with this approach is that I don't have a good way of doing step 3. Matlab doesn't use standard Windows controls so I'm pretty sure something like UI Automation won't help me here. The solution I can think of is to get the client window area of the Matlab instance and send a mouse click in the dead center, since this is within the default positioning of the command window (of course I would make sure it's actually there).  </p>
  
  <p>Still, I realize this is a pretty lousy solution so I'm hoping someone can come up with a better one, preferably without having to click around and assuming things will be where it should be. I've searched around and the solutions to similar questions don't apply well to my case:</p>
  
  <ul>
  <li>I don't want to create new instances of Matlab every time I want to execute a script; I just want to reuse the same instance that is already there.</li>
  <li>I don't want to integrate Matlab code into my C# project since it's doing complicated things involving painting stuff directly to the screen, writing data to parallel ports ...etc</li>
  <li>I'm not sure if I want to use COM to do this since I have no experience with COM at all and don't know where to begin with. Besides, using COM (or DDE for that matter) to pass a single string seems like overkill</li>
  <li>I only have a basic license and don't have access to the fancy toolboxes</li>
  </ul>