Sep 2, 2020 at 7:01am UTC
Hi.
I am trying to change the background image of a form control passing a string variable instead of a litteral string.
Is this possible at all ?
the code i'm trying to use is this:
const std::string test = "C:\\Users\\Pictures\\Tiger.jpg";
Form1.BackgroundImage ->FromFile(test);
many thanks in advance.
Last edited on Sep 2, 2020 at 7:02am UTC
Sep 2, 2020 at 7:48am UTC
Well if a string literal works, then I'm guessing you need something like
Form1.BackgroundImage ->FromFile(test.c_str());
Sep 2, 2020 at 8:06am UTC
I have tried that, but the only thing that works is ::FromFile("Picturename here");
I tried C_str() but got this errror code:
Form1.BackgroundImage ->FromFile(test.c_str());
no instance of overloaded function "System::Drawing::Image::FromFile" matches the argument list Project2 C:\Users\IT\Source\Repos\Project2\MyForm.cpp
I have 400 pictures my program randomly chooses from.
The problem is that i need to switch pictures on 2 forms using them like slides in powerpoint.
Sep 2, 2020 at 9:11am UTC
Ok.
That got rid of the error code, but the forms background image doesn't change. ???
I stepped through the program and i can see that the value of backgroundImage is a Nullptr.
What am i doing wrong ?
this is my code so far:
int main()
{
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Project2::MyForm slide1;
System::String^ test = "C:\\Users\\IT\\Pictures\\testpicture.jpg";
slide1.BackgroundImage->FromFile(test);
Application::Run(% slide1)
}
Last edited on Sep 2, 2020 at 9:41am UTC
Sep 2, 2020 at 10:06am UTC
.c_str() returns a const char* - not char*. If the function requires a char* rather than const char *, then use .data() [for C++17] instead which gives char *. Alternatively cast .c_str() to a char *.
Sep 2, 2020 at 10:52am UTC
Seeplus.
I am not sure i understand what you are writing.
i am not using .c_str() anywhere in my program.
Sep 2, 2020 at 10:58am UTC
seeplus, it's right what you write- in C++, but in .NEt things are different.
@OP, try this:
slid1.BackgroundImage = System::Drawing::Image::FromFile("C:\\Users\\IT\\Pictures\\testpicture.jpg" );
Last edited on Sep 2, 2020 at 11:04am UTC
Sep 2, 2020 at 11:11am UTC
Thomas1965
That works, but this way the filename is locked. I wan't to use a variable so that i can change the background image when my program is running.
Sep 2, 2020 at 11:56am UTC
Found the solution myself.
This doesn't work:
slide1.BackgroundImage->FromFile(test);
But this does:
slide1.BackgroundImage = Image::FromFile(test);code
So the code looks like this:
main
{
Project2::MyForm slide1;
System::String^ test;
test = "C:\\Users\\IT\\Pictures\\TestBilleder\\1.jpg";
slide1.BackgroundImage = Image::FromFile(test);
Application::Run(% slide1);
}
Thanks to those who helped me with my problem.
:o)
Last edited on Sep 2, 2020 at 11:59am UTC