具有优先级参数的CreateProcess?

时间:2012-01-30 16:46:36

标签: delphi delphi-xe

如何通过我的程序创建和运行流程,并能够设置流程的优先级?

这是我到目前为止所做的:

const
  LOW_PRIORITY            = IDLE_PRIORITY_CLASS;
  //BELOW_NORMAL_PRIORITY = ???
  NORMAL_PRIORITY         = NORMAL_PRIORITY_CLASS;
  //ABOVE_NORMAL_PRIROTY  = ???
  HIGH_PRIORITY           = HIGH_PRIORITY_CLASS;
  REALTIME_PRIORITY       = REALTIME_PRIORITY_CLASS;

procedure RunProcess(FileName: string; Priority: Integer);
var
  StartInfo: TStartupInfo;
  ProcInfo: TProcessInformation;
  Done: Boolean;
begin
  FillChar(StartInfo,SizeOf(TStartupInfo),#0);
  FillChar(ProcInfo,SizeOf(TProcessInformation),#0);
  StartInfo.cb := SizeOf(TStartupInfo);
  try
    Done := CreateProcess(nil, PChar(FileName), nil, nil,False,
                          CREATE_NEW_PROCESS_GROUP + Priority,
                          nil, nil, StartInfo, ProcInfo);
    if not Done then
      MessageDlg('Could not run ' + FileName, mtError, [mbOk], 0);
  finally
    CloseHandle(ProcInfo.hProcess);
    CloseHandle(ProcInfo.hThread);
  end;
end;

以上代码的作用是我可以设置执行过程的优先级。但请参阅Windows任务管理器下面的图像:

Screenshot of Task Manager

您可以设置更多选项,例如低于正常和高于正常,这也是我想要设置的。通过Windows.pas看,我没有看到这样的价值。

如何使用这些额外参数创建和运行我的流程?

谢谢:)

2 个答案:

答案 0 :(得分:5)

这两个标志未在Delphi附带的Windows.pas中声明。您必须自己声明这些值。这些值可以在SetPriorityClass的MSDN文档中找到。

const
  BELOW_NORMAL_PRIORITY_CLASS = $00004000
  ABOVE_NORMAL_PRIORITY_CLASS = $00008000

另外请记住,CreateProcess会修改其第二个参数lpCommandLine,即您传递的参数PChar(FileName)。因此,如果调用函数传递一个存在于只读内存中的字符串文字,则代码将失败。我会添加以下行

UniqueString(FileName);

在调用CreateProcess之前。可以在此处找到更多信息:Access Violation in function CreateProcess in Delphi 2009

答案 1 :(得分:-1)

IDLE_PRIORITY_CLASS
BELOW_NORMAL_PRIORITY_CLASS
NORMAL_PRIORITY_CLASS
ABOVE_NORMAL_PRIORITY_CLASS
HIGH_PRIORITY_CLASS
REALTIME_PRIORITY_CLASS

Reference