在其他屏幕上启动程序

时间:2018-09-01 13:33:51

标签: c# winforms pinvoke setwindowpos

我已经签出了:

  

SetWindowPos not working on Form.Show()

     

Launch an application and send it to second monitor?

但是,这些解决方案似乎都不适合我。我想在其他显示器上打开外部程序。

这是我当前的代码:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <direct.h>

using namespace std;

int main()
{   
    // Call gnuplot
    FILE* gnuplotPipe = popen("\"C:\\Program Files\\gnuplot\\bin\\gnuplot\" -persist","w");

    char* cwd = _getcwd( 0, 0 ); // Store current working directory into string 
    string stringCwd(cwd);

    ofstream outFile; // to store the multiplication tables
    string gnuplotCommands; 

    for(int i = 1; i <= 10; i++)
    {
        // Define gnuplot commands
        stringstream figureNumber;
        figureNumber << i; 
        gnuplotCommands = "reset\n"
                          "cd '" + stringCwd + "'\n"
                          "set terminal png size 1920,1080\n"
                          "set output 'Figure" + figureNumber.str() + ".png'\n"
                          "set size 0.5,0.5\n"
                          "set origin 0.25,0.25\n"
                          "plot \"multiplicationTable.dat\" using 1:2 w l lw 2 lc rgb 'blue'\n";

        // Store multiplication table [i*1, i*2, ..., i*10] into .dat file
        outFile.open("multiplicationTable.dat",ios::out);                 
        for(int j = 1; j <= 10; j++)
            outFile << j << " " << i*j << endl; 
        outFile.close();

        // Write gnuplot commands
        fprintf(gnuplotPipe,gnuplotCommands.c_str());
        fflush(gnuplotPipe); //flush pipe 

    }

    fprintf(gnuplotPipe,"exit \n");   // exit gnuplot
    pclose(gnuplotPipe);    //close pipe

    return 0;
}

1 个答案:

答案 0 :(得分:1)

首先,您不需要UpdateWindow,调用SetWindowPos可能就足够了。您只需要确保已创建窗口句柄(因为该进程正在启动)。只需在调用SetWindowPos之前添加以下行即可:

application.WaitForInputIdle();

如果WaitForInputIdle()对您不起作用,您可以尝试以下方法:

while (application.MainWindowHandle == IntPtr.Zero)
{
    await Task.Delay(100);
}

以下代码对我来说很好:

Process application = new Process();
application.StartInfo.UseShellExecute = false;
application.StartInfo.FileName = "notepad.exe";
if (application.Start())
{
    application.WaitForInputIdle();
    /* Optional
    while (application.MainWindowHandle == IntPtr.Zero)
    {
        await Task.Delay(100);
    } */

    Rectangle monitor = Screen.AllScreens[1].Bounds; // for monitor no 2

    SetWindowPos(
        application.MainWindowHandle,
        IntPtr.Zero,
        monitor.Left,
        monitor.Top,
        monitor.Width,
        monitor.Height,
        SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
}

请注意,这只会设置窗口的位置,而不会设置窗口的大小。如果您还希望更改大小,则需要删除SWP_NOSIZE标志。