Okay, I do not know what is causing the crash of my app and I simply do not understand what is happening. I will explain shortly what my app CAN do and what is my problem.
Furthermore I read barely any topic about that on here, and was clicking my way through different google sites.
I am not finding a solution, so I have to ask!
I have an image set as Background -> Works fine.
I have a TextBlock which displays different text every 15 seconds, controlled by a timer, each text is saved in a list! -> Works fine.
I have a fade in/fade out of that text -> Works fine.
I have an application bar at the bottom -> Works fine.
Chaing one explicit picture with that peace of code -> Works fine.
private void Appearance_Click(object sender, EventArgs e)
{
Hintergrund.Source = new BitmapImage(new Uri("/Pictures/StarsNight19.jpg", UriKind.Relative));
}
Well I have around 20 different Images, all have pretty the same names, saved in a folder in my project. The path is as shown in the code fragment: /Pictures/StarsNightXX.jpg
Build Action is set to: CONTENT (well tried everything basically..)
Copy To Output Directory is set to: Copy Always.
Now here is my problem.
I saved the names of my images in a List.
.....
pictures.Add("StarsNight4.jpg");
pictures.Add("StarsNight5.jpg");
pictures.Add("StarsNight6.jpg");
....
I use the same operation as before, wanting it to change the image when clicked on the nice little button in my application bar:
private void Appearance_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int next = rnd.Next(0, pictures.Count - 1);
background.Source = new BitmapImage(new Uri("/Pictures/"+pictures.ElementAt(next), UriKind.RelativeOrAbsolute));
}
BOOM APP CRASHES
I just can not figure out where the problem is.
Changing it by writing an explicit name as shown at the beginning is working out fine...
Maybe someone can tell me if the list is causing a problem?
I just can not figure it out.
"looping it" does not work out either:
int i = 0;
private void Appearance_Click(object sender, EventArgs e)
{
if (i >= pictures.Count) i = 0;
background.Source = new BitmapImage(new Uri("/Pictures/" + pictures.ElementAt(i), UriKind.RelativeOrAbsolute));
i++;
}
Because I am testing my App directly on my WP I do not know what kind of exception I get.
No way compiling and testing it on my computer just to let you know.
...
Losing my mind right here.
Kindly try this source code, I've tried to dispose of the object which are created in the source below, use your list and other code such as loop as it is.
private static BitmapImage bi = null;//this line at the top, not in function
private static Image si = null;//this line at the top, not in function
if bi!=null)
{
bi.Dispose();
bi = null;
}
if si!=null)
{
si.Dispose();
si = null;
}
BitmapImage bi = new BitmapImage();
Image si = new Image();
bi.BeginInit();
bi.UriSource = new Uri(#"/img/img1.jpg",UriKind.RelativeOrAbsolute);
bi.EndInit();
si.Source = bi;
Related
I don't know if I still have missing on this but whenever you want to add PictureBox, you just find it on Toolbox and drag it on the UI. But what I did is I coded it by adding PictureBox then what I want is I have to move it to the right. I coded it on a Timer and this is how I do.
private void enemyMove_Tick(object sender, EventArgs e)
{
GameMenu menu = new GameMenu();
if (menu.cmbox_Level.Text.Equals("Easy"))
{
this.Controls.Add(menu.EnemyTank);
menu.EnemyTank.Width = 26;
menu.EnemyTank.Height = 32;
menu.EnemyTank.BackgroundImage = Properties.Resources.Tank_RIGHT_v_2;
menu.EnemyTank.BackgroundImageLayout = ImageLayout.Stretch;
menu.EnemyTank.Left += 2;
}
}
Don't ask me if the Timer is started. Yes it already started, it was coded on the Form. But somehow when I start the program it doesn't move. But then I tried adding PictureBox, this time I tried dragging it to UI then add an Image on it, then coded it by moving to the right. When I start the program it works. But what I want is that whenever I start the button it will just make the random PictureBox move to the right. Idk what's the missing in here.
I made some assumptions. If I my assumptions aren't correct, please update your post for details. Following content is copied from my comment.
A new GameMenu will always create a new EnemyTank.
A EnemyTank's default Left value is fixed;
Your enemyMove_Tick is keep creating GameMenu and EnemyTank.
That is, every tick, a EnemyTank is created and value changed to "default value plus 2" in your code.
To avoid it, you have to keep EnemyTank instance somewhere instead of keep creating it.
Here's a example.
GameMenu m_menu;
void YourConstructor()
{
// InitializeComponent();
// something else in your form constructor
m_menu = new GameMenu();
m_menu.EnemyTank.Width = 26;
m_menu.EnemyTank.Height = 32;
m_menu.EnemyTank.BackgroundImage = Properties.Resources.Tank_RIGHT_v_2;
m_menu.EnemyTank.BackgroundImageLayout = ImageLayout.Stretch;
this.Controls.Add( m_menu.EnemyTank );
}
private void enemyMove_Tick(object sender, EventArgs e)
{
if (menu.cmbox_Level.Text.Equals("Easy"))
{
m_menu.EnemyTank.Left += 2;
}
}
I have an issue that I think has not been covered in the multitude of other WPF image loading issues. I am scanning in several images and passing them to a "Preview Page". The preview page takes the image thumbnails and displays what a printout would look like via a generated bitmap.
The weird thing to me is, it will work fine if I run the program the first time. Upon reaching the end of the process and hitting "start over", the preview will return blank. I am creating the BitmapImage in a method that saves the bitmap as a random file name so I do not believe theres a lock on the file the second time around. Also, if I go to look at the temporary file created through explorer, it is drawn correctly so I know the appropriate data is getting to it.
Finally, when I navigate away from this page, I am clearing necessary data. I'm really perplexed and any help would be appreciated.
//Constructor
public Receipt_Form() {
InitializeComponent();
printData = new List<Object>();
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void MainWindow_Loaded(object sender, RoutedEventArgs e) {
// populates global variable fileName
var task = System.Threading.Tasks.Task.Factory.StartNew(() => outputToBitmap()); task.ContinueWith(t => setImage(fileName),
System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());
// I started the image creation in a separate thread because I
// thought it may be blocking the UI thread, but it didn't matter
}
private void setImage(string imageURI) {
BitmapImage image;
using (FileStream stream = File.OpenRead(imageURI)) {
image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.CacheOption = BitmapCacheOption.OnLoad;
image.EndInit();
}
receiptPreview.Source = image;
//this works the first iteration but not the second, though the temp file is created successfully
}
Found the issue - the Modern UI container was getting cleared when transitioning off the page.
I want to show an image from Disk !
private void Button_Click_3(object sender, RoutedEventArgs e)
{
myImage.Source = new BitmapImage(
new Uri("images\\Countries\\dz.png",UriKind.Relative));
}
I'm sure that the filename is correct but
when I press the button, The image doesn't appear, I also made sure that the image is in the front of all other control and that myImage is its name .
Try this:
private void Button_Click_3(object sender, RoutedEventArgs e)
{
try
{
myImage.Source = new BitmapImage(
new Uri(#"images\Countries\dz.png",UriKind.Relative));
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Putting # makes it a literal string (you don't need to provide
escape sequence then)
If the above also doesn't work then it'll show the exception if any
occurs.
BitmapImage bitImg = new BitmapImage();
bitImg.BeginInit();
bitImg.UriSource = new Uri("images\\Countries\\dz.png", UriKind.Relative);
bitImg.EndInit();
myImage.Source = bitImg;
A few things that may help you:
Instead of:
myImage.Source = new BitmapImage(new Uri("images\\Countries\\dz.png",UriKind.Relative));
Try This:
BitmapImage ImageName = new BitmapImage;
ImageName.BeginInit();
ImageName.UriSource = new Uri(#"images\Countries\dz.png",UriKind.Relative);
ImageName.EndInit();
myImage.Source = ImageName;
See below link (examples section at the bottom of the page) for more info.
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx
If the above doesn't work, we will need you to post more code :). Also, it would help if you specify exactly what you are trying to achieve here.
Try to Debug it.
Put a break point on the line(F9) and hit F5 to start debugging. Check the value of myImage.Source after the line is executed (F10 to step).
You can also use the Immediate Window to test other statements while debugging is paused and see the results.
Also make sure that the images folder is in the same folder as the executable file (in Debug or Release folders, according to your build)
This seems like a serious bug :
private void LayoutRoot_Drop(object sender, DragEventArgs e)
{
if ((e.Data != null) && (e.Data.GetDataPresent(DataFormats.FileDrop)))
{
FileInfo[] files = (FileInfo[])e.Data.GetData(DataFormats.FileDrop);
using (FileStream fileStream = files[0].OpenRead())
{
//Code reaching this point.
BitmapImage bmpImg = new BitmapImage();
bmpImg.ImageOpened += new EventHandler<RoutedEventArgs>(bmpImg_ImageOpened);
bmpImg.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(bmpImg_ImageFailed);
try
{
bmpImg.SetSource(fileStream);
}
catch
{
//Code dosen't reach here.
}
}
}
}
void bmpImg_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
//Code dosen't reach here.
}
void bmpImg_ImageOpened(object sender, RoutedEventArgs e)
{
//Code dosen't reach here.
}
I am experiencing a very strange behivour. Running this code on my computer, it works - when you drag a JPG on the LayoutRoot I can break inside bmpImg_ImageOpened().
But on a different machine it won't work - when dragging a JPG, I can break in the drop event but after SetSource() nothing happens : no exceptions are thrown, and non of the callbacks are invoked.
I tried it on another machine and it also didn't work.
edit:
On all of the machines, when adding an Image class and setting it's Source property to the bitmapImage, the image is shown fine. so I guess it's an issue with the callbacks. This is not enough because I still need those events.
I am banging my head here, what could it be ?
This is simply how Silverlight has always behaved. ImageOpened only fires if the image is downloaded and decoded (i.e. using Source). It does not fire when using SetSource. If you need access to the dimensions after loading your image either use WriteableBitmap for the PixelWidth and PixelHeight properties (instead of BitmapImage) or do something like:
img.Source = bmpImg;
Dispatcher.BeginInvoke(() =>
{
FakeImageOpened(); // Do logic in here
});
You have to set
bitmapImage.CreateOptions = BitmapCreateOptions.None;
Then the ImageOpened event is fired. This is because the default Options are CreateDelayed
Greetings
Christian
http://www.wpftutorial.net
I develop a Winform Application with the framlework .NET 3.5 in C#.
I would like to allow the user to drag&drop a picture from Word 2007. Basically the user open the docx, select a picture and drag&drop them to my PictureBox.
I've already done the same process with picture files from my desktop and from Internet pages but I can't go through my problem with my Metafile. I've done few researches but I didn't find any solutions solving my issue.
Here is what I've done on my Drag&Drop event :
private void PictureBox_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.MetafilePict)){
Image image = new Metafile((Stream)e.Data.GetData(DataFormats.MetafilePict));
}
}
I can obtain a stream with this code : (Stream)e.Data.GetData(DataFormats.MetafilePict) but I don't know how to convert it into a Metafile or better an Image object.
If you have any idea or solution, I'll be glad to read it.
Thanks,
Here is a working example of Drag n Drop from Word (not for PowerPoint and Excel):
static Metafile GetMetafile(System.Windows.Forms.IDataObject obj)
{
var iobj = (System.Runtime.InteropServices.ComTypes.IDataObject)obj;
var etc = iobj.EnumFormatEtc(System.Runtime.InteropServices.ComTypes.DATADIR.DATADIR_GET);
var pceltFetched = new int[1];
var fmtetc = new System.Runtime.InteropServices.ComTypes.FORMATETC[1];
while (0 == etc.Next(1, fmtetc, pceltFetched) && pceltFetched[0] == 1)
{
var et = fmtetc[0];
var fmt = DataFormats.GetFormat(et.cfFormat);
if (fmt.Name != "EnhancedMetafile")
{
continue;
}
System.Runtime.InteropServices.ComTypes.STGMEDIUM medium;
iobj.GetData(ref et, out medium);
return new Metafile(medium.unionmember, true);
}
return null;
}
private void Panel_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.EnhancedMetafile) & e.Data.GetDataPresent(DataFormats.MetafilePict))
{
Metafile meta = GetMetafile(e.Data);
Image image = meta;
}
}
After this you can use image.Save to save picture or you can use it on picturebox or other control.
I think you need to call new Metafile(stream) as there is no method .FromStream in Metafile.
I'm still digging into he web to try different way to solve my issue.
Hopefully I've found this unanswered thread talking about my problem but without any response :
Get Drag & Drop MS Word image + DataFormats.EnhancedMetafile & MetafilePict :
http://www.codeguru.com/forum/showthread.php?t=456722
I work around with another io be able to copy floating Image (Image stored in Shape and not InlineShape) with Word 2003 and pasting into my winform. I can't paste the link of the second source (because of my low reputation on this website) but I'll do if someone request.
So apparently there are a common issue with the fact that you cannot access to your Metafile stored in the Clipboard and by Drag&Drop.
I still need to understand how to get my Metafile by Drag&Drop.