我有一个TEditbox,其中用户键入文件的某个名称以及他想要保存的扩展名。现在我想验证他输入的扩展名是否是在Windows中注册的有效扩展名。我怎样才能做到这一点?
我只有:
procedure TForm2.OkBtnClick(Sender: TObject);
var
ExtractedFileExt: string;
begin
ExtractedFileExt := ExtractFileExt(cxCbxSelectedFile.Text);
end;
如何使用该字符串变量并检查它是否是在Windows上注册的有效文件扩展名?
答案 0 :(得分:1)
我认为这不是“黑客”注册表。据我所知,如果不从注册表中读取任何值,就没有好的方法可以做你想做的事情。 因此,如果要使用注册表,请使用此代码:
uses Registry;
function GetProgramAssociation(const Ext: string): string;
var reg: TRegistry;
s: string;
begin
s:='';
reg:=TRegistry.Create;
try
reg.RootKey:=HKEY_CLASSES_ROOT;
if reg.OpenKey('.'+ext+'shellopencommand', false) then
begin
s:=reg.ReadString('');
reg.CloseKey;
end
else
begin
if reg.OpenKey('.'+ext, false) then
begin
s:=reg.ReadString('');
reg.CloseKey;
if s='' then
begin
if reg.OpenKey(s+'shellopencommand', false) then
s:=reg.ReadString('');
reg.CloseKey;
end;
end;
end;
if Pos('%', s) > 0 then Delete(s, Pos('%', s), length(s));
if ((length(s)>0) and (s[1]='"')) then Delete (s, 1, 1);
if ((length(s)>0) and (s[length(s)]='"')) then Delete(s, Length(s), 1);
while ((length(s)>0) and ((s[length(s)]=#32) or (s[length(s)]='"'))) do
Delete(s, Length(s), 1);
result:=s;
finally
reg.Free;
end;
end;
然后:
if GetProgramAssociation(Extension) = '' then
ShowMessage('Nope!');
工作正常。 如果Extension与有效程序无关,则返回空字符串。 例如,如果输入'doc'(不带'。'),则返回 Word.Document.8如果输入'abcdef'则不返回任何内容('')。
不要忘记:放入没有点的扩展名