Set a TIcon image from a string variable

I need to be able to setup the image of a TIcon at execution time.
The content of the equivalent icon file (something.ico) will be in a string variable, but I don't want to go the steps : write the string to a file and loadfromfile method.
Is there a way ?
LVL 1
LeTayAsked:
Who is Participating?
 
geobulConnect With a Mentor Commented:
Hi,

Try something like:

var
  st: TStringStream;
  s: string;
  icon: TIcon;
...
begin
  s := 'asd'; // assign the contents here

  st:= TStringStream.Create(s);
  try
   icon.LoadFromStream(st);
  finally
    st.Free;
  end;
end;

Regards, Geo
0
 
mikelittlewoodCommented:
You could store the icon or a selection of icons in a .res file if you dont want to load it directly from a file.

Then you could call
Image1.Picture.Icon.Handle := LoadIcon(HInstance ,'ICON_1');

Make sure you list the res file under the {$R *.dfm}
{$R myres.res}
0
 
mikelittlewoodCommented:
You can also store icons in a TImageList and assign it at runtime to the index of the imagelist

var
  icTest: TIcon;
begin
  icTest := TIcon.Create;
  ImageList1.GetIcon(0, icTest);
  Application.Icon := icTest;

You can change the 0 to whatever the position of the icon in the list is
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
LeTayAuthor Commented:
In my case I need a string as it will be a kind of constant somewhere in a DLL
0
 
mikelittlewoodCommented:
Well if you used the .res file method, you can pass in the name of the string (without .ico)

Image1.Picture.Icon.Handle := LoadIcon(HInstance ,<YourIconName>);
0
 
mikelittlewoodCommented:
0
 
LeTayAuthor Commented:
Thank you geobul, your code works perfectly well and it is exactly what I need..
0
 
geobulCommented:
You are welcome. I'm glad to hear that. Have a nice day :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.