Converting a vb.Net Project to C# .Net Project - c#

I've tried converting vb.net to C# but I keep getting error while compiling. I am new to .NET.
This is my version of converted image utilities class. Util.cs
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using Com.Griaule.IcaoFace;
using System.Windows.Forms;
namespace IcaoWF
{
public class Util
{
//Set if the mouth is important
public const bool USES_MOUTH = true;
//The number of supported pictures
const int SFile = 3;
//
public const int FEATURES_COLOR = (255 << 8);
public const int FEATURES_SIZE = 8;
//File Vector with spec ID
TFile[] VTFile = new TFile[SFile + 1];
//Pointers to the .NET classes
public FaceImage GrFaceImage = null;
public IcaoImage GrIcaoImage = null;
public CbeffImage GrCbeffImage = null;
public Cbeff GrCbeff = null;
ListBox log;
// raw image data type.
public struct TRawImage
{
// Image data.
public object img;
// Image width.
public int width;
// Image height.
public int height;
//Reduction Factor because stretch
public float frX;
public float frY;
//Eyes an mouth positions
public int lx;
public int ly;
public int rx;
public int ry;
public int mx;
public int my;
}
// File Enum Type
public enum EFile
{
BMP = 1,
JPEG2000 = 2,
CBEFF = 3,
NOTDEF = 0
}
//File Type
private struct TFile
{
//File Extension
public string fileExt;
//File Type
public EFile fileID;
}
//Class constructor
public Util(ListBox ltBox)
{
//Adding Supportted files
VTFile[1].fileExt = ".bmp";
VTFile[1].fileID = EFile.BMP;
VTFile[2].fileExt = ".jp2";
VTFile[2].fileID = EFile.JPEG2000;
VTFile[3].fileExt = ".cbeff";
VTFile[3].fileID = EFile.CBEFF;
log = ltBox;
}
public void WriteError(GriauleIcaoFaceException err)
{
WriteLog("Error: " + err.ToString());
}
// Write a message in box.
public void WriteLog(string message)
{
log.Items.Add(message);
log.SelectedIndex = log.Items.Count - 1;
log.ClearSelected();
}
//Get the ID File Type from file path name
public EFile GetFileType(string fileName)
{
EFile functionReturnValue = default(EFile);
int i = 0;
for (i = 0; i <= SFile; i++)
{
if (Strings.InStr(1, fileName, VTFile[i].fileExt) == Strings.Len(fileName) - Strings.Len(VTFile[i].fileExt) + 1)
{
functionReturnValue = VTFile[i].fileID;
return functionReturnValue;
}
}
functionReturnValue = EFile.NOTDEF;
return functionReturnValue;
}
//Loading an Image
public bool LoadImage(string fileName, PictureBox img)
{
// create face image from file
GrFaceImage = new FaceImage(fileName);
// display face image
DisplayFaceImage(img, false);
WriteLog("Image loaded successfully.");
return true;
}
//Process the raw Image to FaceImage Type and paint the points on pBox
public bool ProcessFaceImage(PictureBox pBox)
{
//Set mouth to be relevant to generate the ICAO
GrFaceImage.MouthDetectionEnabled = USES_MOUTH;
WriteLog("Finding the eyes and mouth positions. Please, wait...");
//Get the positions from mouth and eyes
if (GetPositionsFromFaceImage())
{
WriteLog("Eyes and mouth founded. Drawing their positions on the image.");
//Display Face Image with eyes and mouth drawn
DisplayFaceImage(pBox, true);
return true;
}
else
{
//Display Face Image
DisplayFaceImage(pBox, false);
return false;
}
}
//Display the ICAO Image
public void DisplayIcaoImg(PictureBox imgIcao)
{
if (GrFaceImage.LeftEye.X <= 0 | GrFaceImage.LeftEye.Y <= 0 | GrFaceImage.LeftEye.X > GrFaceImage.Width | GrFaceImage.LeftEye.Y > GrFaceImage.Height)
{
WriteLog("Left eye is out of bounds.");
return;
}
if (GrFaceImage.RightEye.X <= 0 | GrFaceImage.RightEye.Y <= 0 | GrFaceImage.RightEye.X > GrFaceImage.Width | GrFaceImage.RightEye.Y > GrFaceImage.Height)
{
WriteLog("Right eye is out of bounds.");
return;
}
if (GrFaceImage.Mouth.X <= 0 | GrFaceImage.Mouth.Y <= 0 | GrFaceImage.Mouth.X > GrFaceImage.Width | GrFaceImage.Mouth.Y > GrFaceImage.Height)
{
WriteLog("Mouth is out of bounds.");
return;
}
//Get the GrIcaoImage
try
{
GrIcaoImage = GrFaceImage.FullFrontalImage(imgIcao.Width, 3.0 / 4.0, IcaoImage.IcaoFullFrontalMode.FullFrontal);
}
catch (GriauleIcaoFaceException ex)
{
WriteError(ex);
return;
}
//Getting the eyes positons from icao
if (GetPositionsFromIcaoImage())
{
//Displaying the icao image
DisplayIcaoImage(imgIcao);
}
WriteLog("ICAO image generated.");
}
//Display Face Image
public void DisplayFaceImage(PictureBox pBox, bool withFeatures)
{
if (withFeatures)
{
pBox.Image = GrFaceImage.ImageWithFeatures(8, Color.Green);
}
else
{
pBox.Image = GrFaceImage.Image;
}
pBox.Update();
}
//Display Cbeff Image
public void DisplayCbeffImage(PictureBox pBox)
{
pBox.Image = GrCbeffImage.Image;
pBox.Update();
}
//Display Icao Image
public void DisplayIcaoImage(PictureBox pBox)
{
pBox.Image = GrIcaoImage.Image;
pBox.Update();
}
//Save ICAO in CBEFF file format
public void SaveIcaoIntoCBEFFImage(string fileName)
{
// Create a CBEFF from Icao
if (GetCbeffFromIcao())
{
//Get the CBEFF buffer
try
{
SaveBuffer(fileName, ref GrCbeff.CBEFF);
}
catch (GriauleIcaoFaceException ex)
{
WriteError(ex);
}
}
}
//Load an ICAO image from CBEFF file format
public void LoadIcaoFromCBEFFImage(string fileName, PictureBox pBox)
{
//Creating the cbeff from the buffer
try
{
GrCbeff = new Cbeff(LoadBuffer(fileName));
GrCbeffImage = GrCbeff.Image(0);
}
catch (GriauleIcaoFaceException ex)
{
WriteError(ex);
}
// Display icao image
DisplayCbeffImage(pBox);
}
//Save ICAO image in JPEG2000 file format
public void SaveIcaoIntoJP2Image(string fileName)
{
// Create a CBEFF from Icao
if (!GetCbeffFromIcao())
{
return;
}
//Get Jpeg2000 buffer from CBEFF and save it in a file
SaveBuffer(fileName, ref GrCbeffImage.BufferJPEG);
}
//Save Byte Buffer into a file
private void SaveBuffer(string fileName, ref byte[] buffer)
{
System.IO.FileStream oFileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
System.IO.BinaryWriter swb = new System.IO.BinaryWriter(oFileStream);
swb.Write(buffer);
swb.Close();
}
//Load stream from file
private byte[] LoadBuffer(string fileName)
{
// Open a file that is to be loaded into a byte array
FileInfo oFile = null;
oFile = new FileInfo(fileName);
System.IO.FileStream oFileStream = oFile.OpenRead();
long lBytes = oFileStream.Length;
byte[] fileData = new byte[lBytes + 1];
// Read the file into a byte array
oFileStream.Read(fileData, 0, lBytes);
oFileStream.Close();
return fileData;
}
//Get CBEFF image from an Icao image
private bool GetCbeffFromIcao()
{
//Create Cbeff Image Data pointer
GrCbeff = new Cbeff();
GrCbeffImage = GrCbeff.AddImage(GrIcaoImage, false, 0);
GrCbeffImage.Gender = CbeffImage.CbeffGender.Unknown;
GrCbeffImage.Eyes = CbeffImage.CbeffEyes.Unspecified;
GrCbeffImage.Hair = CbeffImage.CbeffHair.Unspecified;
GrCbeffImage.FeatureMask = 0;
GrCbeffImage.Expression = CbeffImage.CbeffExpression.Unspecified;
return true;
}
//Get eyes and mouth position from Face Image
public bool GetPositionsFromFaceImage()
{
float prob = 0;
//Get the eyes detection probabilty
prob = GrFaceImage.DetectionProbability;
if (prob == 0)
{
Interaction.MsgBox("There isn't any probability to find the eyes position.", Constants.vbCritical, "No probability");
return false;
}
return true;
}
//Get eyes and mouth position from ICAO Image
public bool GetPositionsFromIcaoImage()
{
//get the position from an icao image.
float prob = 0;
prob = GrIcaoImage.DetectionProbability;
if (prob <= 0)
{
WriteLog("There isn't any probability to find the eyes position.");
return false;
}
return true;
}
//Set left eye position on library
public void SetLeftEyePos(int x, int y)
{
GrFaceImage.LeftEye = new Point(x, y);
}
//Set right eye position on library
public void SetRightEyePos(int x, int y)
{
GrFaceImage.RightEye = new Point(x, y);
}
//Set mouth position on library
public void SetMouthPos(int x, int y)
{
if (x > 0 & x < GrFaceImage.Width & y > 0 & y < GrFaceImage.Height)
{
Point p = new Point(x, y);
GrFaceImage.Mouth = p;
}
}
//Marshal between library and VB .NET. Copy an Variant Array to Byte() vector
public byte[] ConvertArrayToVByte(Array buffer)
{
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
byte[] bytes = new byte[buffer.Length + 1];
Marshal.Copy(ptr, bytes, 0, bytes.Length);
return bytes;
}
// Show GriauleAfis version and type
public void MessageVersion()
{
int majorVersion = 0;
int minorVersion = 0;
GriauleIcaoFace.GetVersion(majorVersion, minorVersion);
MessageBox.Show("The GrIcaoFace DLL version is " + majorVersion + "." + minorVersion + ".", "GrIcaoFace Version", MessageBoxButtons.OK);
}
}
}
I keep get error with this error:
The type or namespace name 'ListBox' could not be found (are
you missing a using directive or an assembly reference?).
The type or namespace name 'PictureBox' could not be found (are you
missing a using directive or an assembly reference?).
And here is the formMain.cs
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace IcaoWF
{
public partial class formMain : Form
{
public formMain(): base()
{
Load += formMain_Load;
InitializeComponent();
}
// raw image data type.
private struct TSetting
{
// Image data.
public Button button;
// Image width.
public Label x;
public Label y;
public bool setting;
}
TSetting CSetting = new TSetting();
Util myUtil = default(Util);
private void formMain_Load(Object sender, EventArgs e)
{
InitializeInterface();
//Setting file filters
ldImg.Filter = "JPEG Images (*.jpg,*.jpeg)|*.jpg;*.jpeg|Gif Images (*.gif)|*.gif|Bitmaps (*.bmp)|*.bmp";
ldIcaoImg.Filter = "CBEFF (*.cbeff)|*.cbeff";
svIcaoImg.Filter = "JPEG2000 (*.jp2)|*.jp2|CBEFF (*.cbeff)|*.cbeff";
myUtil = new Util(logBox);
//Verifieing if the mouth is important
gbMouth.Enabled = myUtil.USES_MOUTH;
}
//Unlock the interface and update the clicked iten
private void interfaceSetStop(int x, int y)
{
if (CSetting.setting) {
//Set the CSetting to false
CSetting.setting = false;
//Set positions from mouse to CSetting text selected
CSetting.x.Text = x.ToString();
CSetting.y.Text = y.ToString();
//Enable Set button again
CSetting.button.Enabled = true;
//Set the normal cursor above image
imgFace.Cursor = Cursors.Arrow;
//Enable all butons, disabled before
EnableButtons();
//Sets new position from image
myUtil.SetLeftEyePos(lbLeftEyeXPos.Text, lbLeftEyeYPos.Text);
myUtil.SetRightEyePos(lbRightEyeXPos.Text, lbRightEyeYPos.Text);
if (myUtil.USES_MOUTH) {
myUtil.SetMouthPos(lbMouthXPos.Text, lbMouthYPos.Text);
}
//Redraw img
myUtil.DisplayFaceImage(imgFace, true);
}
}
//Initialize the program interface
private void InitializeInterface()
{
//Disable butons
DisableButtons();
//Disbable image picture box
imgFace.Enabled = false;
//Current setting eye or mouth to false
CSetting.setting = false;
//Disable Save ICAO image
mnFileSaveIcaoImg.Enabled = false;
//Reset the logBox
logBox.ResetText();
}
//Enable all butons from interface
private void EnableButtons()
{
btGenIcaoImage.Enabled = true;
btLeftEyeSet.Enabled = true;
btMouthSet.Enabled = true;
btRightEyeSet.Enabled = true;
btProcess.Enabled = true;
imgFace.Enabled = true;
}
//Set the inteface to click on the image
private void btLeftEyeSet_Click(Object sender, EventArgs e)
{
interfaceSetStart(btLeftEyeSet, lbLeftEyeXPos, lbLeftEyeYPos);
}
//Set the inteface to click on the image
private void lbRightEyeSet_Click(Object sender, EventArgs e)
{
interfaceSetStart(btRightEyeSet, lbRightEyeXPos, lbRightEyeYPos);
}
//Set the inteface to click on the image
private void btMouthSet_Click(Object sender, EventArgs e)
{
interfaceSetStart(btMouthSet, lbMouthXPos, lbMouthYPos);
}
//Lock the interface to click on image
private void interfaceSetStart(Button button, Label x, Label y)
{
//Set the clicked button set
CSetting.button = button;
//set the label to update the position
CSetting.x = x;
CSetting.y = y;
//Enable set mode
CSetting.setting = true;
//Disable the button
button.Enabled = false;
//Enable Cross cursor on image
imgFace.Cursor = Cursors.Cross;
//Disable button to avoid user to click in another area
DisableButtons();
}
//Disable all buttons from interface
private void DisableButtons()
{
btGenIcaoImage.Enabled = false;
btLeftEyeSet.Enabled = false;
btMouthSet.Enabled = false;
btRightEyeSet.Enabled = false;
btProcess.Enabled = false;
}
//On click on the image, stop the interface and set the right position
private void imgFace_MouseDown(object sender, MouseEventArgs e)
{
interfaceSetStop(e.X / (imgFace.Width / myUtil.GrFaceImage.Width), e.Y / (imgFace.Height / myUtil.GrFaceImage.Height));
}
//Gen the ICAO image from FaceImage
private void btGenIcaoImage_Click(Object sender, EventArgs e)
{
//Display ICAO image captured
myUtil.DisplayIcaoImg(imgIcaoImg);
//Enabled
mnFileSaveIcaoImg.Enabled = true;
}
//Load Icao IMAGE From CBEFF or JPEG2000
private void mnFileLoadIcaoImg_Click(Object sender, EventArgs e)
{
Util.EFile fileType = default(Util.EFile);
ldIcaoImg.FileName = "";
//save the ICAO image
if (ldIcaoImg.ShowDialog == DialogResult.OK & !string.IsNullOrEmpty(ldIcaoImg.FileName))
{
fileType = myUtil.GetFileType(ldIcaoImg.FileName);
switch (fileType)
{
case Util.EFile.CBEFF:
//Save CBEFF image
myUtil.LoadIcaoFromCBEFFImage(ldIcaoImg.FileName, imgIcaoImg);
break;
//
default:
//Image type not found
myUtil.WriteLog("File type not supported.");
return;
}
}
}
//Save ICAO Image
private void mnFileSaveIcaoImg_Click(Object sender, EventArgs e)
{
Util.EFile fileType = default(Util.EFile);
svIcaoImg.FileName = "";
//save the ICAO image
if (svIcaoImg.ShowDialog == DialogResult.OK & !string.IsNullOrEmpty(svIcaoImg.FileName))
{
fileType = myUtil.GetFileType(svIcaoImg.FileName);
switch (fileType)
{
case Util.EFile.CBEFF:
//Save CBEFF image
myUtil.SaveIcaoIntoCBEFFImage(svIcaoImg.FileName);
break;
case Util.EFile.JPEG2000:
//Save JPEG200 image
myUtil.SaveIcaoIntoJP2Image(svIcaoImg.FileName);
break;
default:
//Image type not found
myUtil.WriteLog("File type not supported.");
break;
}
}
}
//Load Image
private void mnFileLoadImg_Click(Object sender, EventArgs e)
{
lbLeftEyeXPos.Text = "0";
lbLeftEyeYPos.Text = "0";
lbRightEyeXPos.Text = "0";
lbRightEyeYPos.Text = "0";
lbMouthXPos.Text = "0";
lbMouthYPos.Text = "0";
//Disable buttons
DisableButtons();
//Enable image
imgFace.Enabled = true;
//Set file name image to null
ldImg.FileName = "";
if (ldImg.ShowDialog == DialogResult.OK & !string.IsNullOrEmpty(ldImg.FileName))
{
//load image from FileName into imgFace Picture Box
if (myUtil.LoadImage(ldImg.FileName, imgFace))
{
//Set the icaoImage to null
imgIcaoImg.Image = null;
imgIcaoImg.Refresh();
//Disble mnFileSaveIcaoImg to save
mnFileSaveIcaoImg.Enabled = false;
//Disable buttons
DisableButtons();
//Enable find eyes and mouth button
btProcess.Enabled = true;
}
}
}
//Close the program
private void MenuItem5_Click(Object sender, EventArgs e)
{
this.Close();
}
//Process the Face Image
private void btProcess_Click(Object sender, EventArgs e)
{
//Enable buttons to set eyes and mouth
EnableButtons();
//Process face image
if (myUtil.ProcessFaceImage(imgFace))
{
//Get positions from face image
lbLeftEyeXPos.Text = myUtil.GrFaceImage.LeftEye.X.ToString();
lbLeftEyeYPos.Text = myUtil.GrFaceImage.LeftEye.Y.ToString();
lbRightEyeXPos.Text = myUtil.GrFaceImage.RightEye.X.ToString();
lbRightEyeYPos.Text = myUtil.GrFaceImage.RightEye.Y.ToString();
lbMouthXPos.Text = myUtil.GrFaceImage.Mouth.X.ToString();
lbMouthYPos.Text = myUtil.GrFaceImage.Mouth.Y.ToString();
}
}
//Print the DLL version
private void mnVersion_Click(Object sender, EventArgs e)
{
myUtil.MessageVersion();
}
}
}
I can post the vb.net version if needed.
EDITED: I have added refference(System.Windows.Forms.dll) to the project and all the other am using.
thanx
Nurcky

ListBox is defined in the assembly System.Windows.Forms.dll. Make sure you have a reference to that assembly.
Additionally you probably want
using System.Windows.Forms;

Both the ListBox and PictureBox controls are found in the System.Windows.Forms namespace. Add the following statement to the top of your code:
using System.Windows.Forms;
Then add a reference to System.Windows.Forms.dll

Use the System.Windows.Forms namespace. To use the System.Windows.Forms namespace, you have to add System.Windows.Forms.dll as a reference.
To add the reference,follow the following step:
In Solution Explorer, right-click on the project node and click Add Reference.
In the Add Reference dialog box, select the .NET tab and choose System.Windows.Forms and click OK.

Related

Images slideshow with fade animation

I am writing a theater mode section in music player. The requirements is to loop through a folder containing images of any type(png, jpeg, gif) and show in a picture box with 5 seconds delay for images of type (png,jpeg) and delay time for gif should be the actual gif time duration. Also there should be fade transition between images when switch from one image to another in a single picture box. All need to be done when software is idle lets say for 60 seconds
Problem
Currently the playing song directory has 'img' folder containing 3 png
images and 3 gif. The first attempt to read
Helper.theaterImagesInfo.ToList() works pretty well
foreach (var img in Helper.theaterImagesInfo.ToList())
It starts to display 3 png images with 5 seconds delay and gif images
with the actual gif duration delay. but if i click picturebox to close theaterform as soon as the form is opened again after 60 seconds of idle state of software and loop continue
to iterate again. The default image is shown with
starting 2 png images from 'img' folder the 3rd png is skipped and then 4th gif starts
to play for few seconds not the actual gif duration and continued in wrong order as well as incorrect delay, Seems like while loop is always running in background. therfore it becomes choppy.
Desired Solution
Whenever i play song theaterform should be displayed and start to show images from folder ( in the same sequence and delay) even if the theaterform is opened again after 60 seconds if the song is still playing. Also if there is a way to show fade when changing image in a single picturebox
Code here
Program.cs
internal static class Program
{
public static Timer IdleTimer = new Timer();
readonly static int miliseconds =
Convert.ToInt32(TimeSpan.FromSeconds(60).TotalMilliseconds);
internal static MainForm f = null;
static public TheaterForm tf;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MessageFilter limf = new MessageFilter();
Application.AddMessageFilter(limf);
Application.Idle += new EventHandler(Application_Idle);
IdleTimer.Interval = miliseconds;
IdleTimer.Tick += TimeDone;
IdleTimer.Start();
f = new MainForm();
tf = new TheaterForm();
var app = new MyApplication();
app.Run(Environment.GetCommandLineArgs());
Application.Idle -= new EventHandler(Application_Idle);
}
static private void Application_Idle(Object sender, EventArgs e)
{
if (!IdleTimer.Enabled) // not yet idling?
IdleTimer.Start();
}
static private void TimeDone(object sender, EventArgs e)
{
IdleTimer.Stop();
if (MainForm.waveOut.PlaybackState == PlaybackState.Playing)
{
if (!Helper.IsTheaterOpen)
{
if (Form.ActiveForm == f)
{
Helper.IsTheaterOpen = true;
tf.WindowState = FormWindowState.Maximized;
tf.Bounds = Screen.PrimaryScreen.Bounds;
tf.x = 1;
tf.ShowDialog(f);
}
}
}
else
{
if (!Helper.IsTheaterOpen)
{
if (Form.ActiveForm == f)
{
Helper.IsTheaterOpen = true;
tf.WindowState = FormWindowState.Maximized;
tf.Bounds = Screen.PrimaryScreen.Bounds;
tf.x = 0;
tf.ShowDialog(f);
}
}
}
}
}
public class MyApplication : WindowsFormsApplicationBase
{
protected override void OnCreateMainForm()
{
MainForm = Program.f;
}
protected override void OnCreateSplashScreen()
{
SplashScreen = new SplashForm();
}
}
Helper.cs
internal class Helper
{
public static bool IsTheaterOpen { get; set; }
public struct ImageInfo
{
public bool IsAnimated;
public int durationInMilliseconds;
public Image ImageHere;
}
public static List<ImageInfo> theaterImagesInfo = new List<ImageInfo>(10);
}
MainForm.cs
/*
* Every song directory has one folder named img that contains images and gif relevant
to the song album
*/
private int GetGifDuration(Image img)
{
int delay = 0, this_delay = 0, index = 0;
FrameDimension frameDimension = new FrameDimension(img.FrameDimensionsList[0]);
int frameCount = img.GetFrameCount(frameDimension);
for (int f = 0; f < frameCount; f++)
{
this_delay = BitConverter.ToInt32(img.GetPropertyItem(20736).Value, index) * 10;
delay += (this_delay < 100 ? 100 : this_delay); // Minimum delay is 100 ms
index += 4;
}
return delay;
}
private void PlayAudio()
{
// Getting images from folder and storing in struct on every song play
if (Directory.Exists(Path.GetDirectoryName(CurrentPlayingMusicUrl) + "\\img"))
{
var files =
Directory.EnumerateFiles(Path.GetDirectoryName(CurrentPlayingMusicUrl) +
"\\img", "*", SearchOption.AllDirectories).Where(s => s.EndsWith(".png") ||
s.EndsWith(".jpg") || s.EndsWith(".jpeg") || s.EndsWith(".gif"));
Helper.theaterImagesInfo.Clear();
foreach (var imagePath in files.ToArray())
{
using (System.Drawing.Image image = System.Drawing.Image.FromFile(imagePath))
{
if (image.RawFormat.Equals(ImageFormat.Gif))
{
Helper.theaterImagesInfo.Add(new Helper.ImageInfo { IsAnimated = true, durationInMilliseconds = GetGifDuration(image), ImageHere = Image.FromFile(imagePath) });
}
else
{
Helper.theaterImagesInfo.Add(new Helper.ImageInfo { IsAnimated = false, durationInMilliseconds = 5000, ImageHere = Image.FromFile(imagePath) });
}
}
}
}
else
{
Helper.theaterImagesInfo.Clear();
Program.tf.x = 0;
}
}
TheaterForm.cs
public partial class TheaterForm : Form
{
public TheaterForm()
{
InitializeComponent();
SetDefaultImage();
}
/*
* Getting Default image from top(root) directory ex. AllMusic. If no 'img' folder
found in song album directory ex. AllMusic -> Justin Bieber -> (img folder not
exist)song1, song2, song3 etc.
*/
private async void SetDefaultImage()
{
string path = KJ_Player.Properties.Settings.Default["MusicFolder"] + "\\img";
if (Directory.Exists(path))
{
var files = Directory.EnumerateFiles(path, "*",
SearchOption.AllDirectories).Where(s => s.EndsWith(".png") ||
s.EndsWith(".jpg") || s.EndsWith(".jpeg"));
await Task.Run(() =>
{
if(files != null && files.Count()>0)
{
PictureBox1.Image = Image.FromFile(files.FirstOrDefault());
}
});
}
}
public int x=1;
private async void TheaterForm_Shown(object sender, EventArgs e)
{
if (this.PictureBox1.Image == null) SetDefaultImage();
if (Helper.theaterImagesInfo != null && Helper.theaterImagesInfo.Count > 0)
{
while (x == 1)
{
foreach (var img in Helper.theaterImagesInfo.ToList())
{
if (img.IsAnimated)
{
try
{
this.PictureBox1.Image = img.ImageHere;
await Task.Delay(img.durationInMilliseconds);
}
catch { }
}
else
{
try
{
await Task.Delay(img.durationInMilliseconds);
this.PictureBox1.Image = img.ImageHere;
}
catch { }
}
}
}
SetDefaultImage();
}
}
private void PictureBoxTheater_Click(object sender, EventArgs e)
{
this.x = 0;
if (this.PictureBox1.Image != null) this.PictureBox1.Image=null;
Helper.IsTheaterOpen = false;
this.Close();
}
}
Most likely you just need to break out of that foreach loop:
foreach (var img in Helper.theaterImagesInfo.ToList())
{
if (img.IsAnimated)
{
try
{
this.PictureBox1.Image = img.ImageHere;
await Task.Delay(img.durationInMilliseconds);
}
catch { }
}
else
{
try
{
await Task.Delay(img.durationInMilliseconds);
if (this.x == 1) {
this.PictureBox1.Image = img.ImageHere;
}
}
catch { }
}
if (this.x == 0) {
break; // exit the for loop early
}
}

Scanning with C# and WIA

I'm trying to scan A4 pages from a C# application using a flat bed scanner and Windows 10. To speed things up, I use the ScanWIA library found here: https://scanwia.codeplex.com/
However, I have huge problems configuring the page settings correctly.
Setting the page size (WIA ID 3097) to AUTO, gives me an "property not supported" exception.
Setting horizontal and vertical extend (WIA ID 6151, 6152) gives me either too small (cropped) results or an "value out of range" exception.
What is the correct way to set this up for A4 pages and variable DPI settings?
How do I set the size of the captured area correctly?
How do I control the size of the output image?
Which setting uses which unit? What are the maximum value ranges?
MSDN is not very helpful on these topics...
I have made a user control to scan the documents from attached scanner.
Here I can explain the details.
In the attached form image there are 2 picture boxes, a preview button, a save button, two labels for showing save path and a drop down to show available scanner devices. See the image above to get a clear picture about the form design.
There is a class file named WIAScanner.cs, see the the code below
using System;
using System.Collections.Generic;
using System.IO;
using System.Drawing;
using WIA;
namespace TESTSCAN
{
class WIAScanner
{
const string wiaFormatBMP = "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}";
const string WIA_DEVICE_PROPERTY_PAGES_ID = "3096";
const string WIA_SCAN_BRIGHTNESS_PERCENTS = "6154";
const string WIA_SCAN_CONTRAST_PERCENTS = "6155";
const string WIA_SCAN_COLOR_MODE = "6146";
class WIA_DPS_DOCUMENT_HANDLING_SELECT
{
public const uint FEEDER = 0x00000001;
public const uint FLATBED = 0x00000002;
}
class WIA_DPS_DOCUMENT_HANDLING_STATUS
{
public const uint FEED_READY = 0x00000001;
}
class WIA_PROPERTIES
{
public const uint WIA_RESERVED_FOR_NEW_PROPS = 1024;
public const uint WIA_DIP_FIRST = 2;
public const uint WIA_DPA_FIRST = WIA_DIP_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
public const uint WIA_DPC_FIRST = WIA_DPA_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
//
// Scanner only device properties (DPS)
//
public const uint WIA_DPS_FIRST = WIA_DPC_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
public const uint WIA_DPS_DOCUMENT_HANDLING_STATUS = WIA_DPS_FIRST + 13;
public const uint WIA_DPS_DOCUMENT_HANDLING_SELECT = WIA_DPS_FIRST + 14;
}
//public void SetProperty(Property property, int value)
//{
// IProperty x = (IProperty)property;
// Object val = value;
// x.set_Value(ref val);
//}
/// <summary>
/// Use scanner to scan an image (with user selecting the scanner from a dialog).
/// </summary>
/// <returns>Scanned images.</returns>
public static List<Image> Scan()
{
WIA.ICommonDialog dialog = new WIA.CommonDialog();
WIA.Device device = dialog.ShowSelectDevice(WIA.WiaDeviceType.UnspecifiedDeviceType, true, false);
if (device != null)
{
return Scan(device.DeviceID,1);
}
else
{
throw new Exception("You must select a device for scanning.");
}
}
/// <summary>
/// Use scanner to scan an image (scanner is selected by its unique id).
/// </summary>
/// <param name="scannerName"></param>
/// <returns>Scanned images.</returns>
public static List<Image> Scan(string scannerId, int pages)
{
List<Image> images = new List<Image>();
bool hasMorePages = true;
int numbrPages = pages;
while (hasMorePages)
{
// select the correct scanner using the provided scannerId parameter
WIA.DeviceManager manager = new WIA.DeviceManager();
WIA.Device device = null;
foreach (WIA.DeviceInfo info in manager.DeviceInfos)
{
if (info.DeviceID == scannerId)
{
// connect to scanner
device = info.Connect();
break;
}
}
// device was not found
if (device == null)
{
// enumerate available devices
string availableDevices = "";
foreach (WIA.DeviceInfo info in manager.DeviceInfos)
{
availableDevices += info.DeviceID + "\n";
}
// show error with available devices
throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices);
}
SetWIAProperty(device.Properties, WIA_DEVICE_PROPERTY_PAGES_ID, 1);
WIA.Item item = device.Items[1] as WIA.Item;
AdjustScannerSettings(item, 150, 0, 0, 1250, 1700, 0, 0, 1);
try
{
// scan image
WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);
// save to temp file
string fileName = Path.GetTempFileName();
File.Delete(fileName);
image.SaveFile(fileName);
image = null;
// add file to output list
images.Add(Image.FromFile(fileName));
}
catch (Exception exc)
{
throw exc;
}
finally
{
item = null;
//determine if there are any more pages waiting
WIA.Property documentHandlingSelect = null;
WIA.Property documentHandlingStatus = null;
foreach (WIA.Property prop in device.Properties)
{
if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT)
documentHandlingSelect = prop;
if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS)
documentHandlingStatus = prop;
}
// assume there are no more pages
hasMorePages = false;
// may not exist on flatbed scanner but required for feeder
if (documentHandlingSelect != null)
{
// check for document feeder
if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0)
{
hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0);
}
}
}
numbrPages -= 1;
if (numbrPages > 0)
hasMorePages = true;
else
hasMorePages = false;
}
return images;
}
/// <summary>
/// Gets the list of available WIA devices.
/// </summary>
/// <returns></returns>
public static List<string> GetDevices()
{
List<string> devices = new List<string>();
WIA.DeviceManager manager = new WIA.DeviceManager();
foreach (WIA.DeviceInfo info in manager.DeviceInfos)
{
devices.Add(info.DeviceID);
}
return devices;
}
private static void SetWIAProperty(WIA.IProperties properties,
object propName, object propValue)
{
WIA.Property prop = properties.get_Item(ref propName);
prop.set_Value(ref propValue);
}
private static void AdjustScannerSettings(IItem scannnerItem, int scanResolutionDPI, int scanStartLeftPixel, int scanStartTopPixel,
int scanWidthPixels, int scanHeightPixels, int brightnessPercents, int contrastPercents, int colorMode)
{
const string WIA_SCAN_COLOR_MODE = "6146";
const string WIA_HORIZONTAL_SCAN_RESOLUTION_DPI = "6147";
const string WIA_VERTICAL_SCAN_RESOLUTION_DPI = "6148";
const string WIA_HORIZONTAL_SCAN_START_PIXEL = "6149";
const string WIA_VERTICAL_SCAN_START_PIXEL = "6150";
const string WIA_HORIZONTAL_SCAN_SIZE_PIXELS = "6151";
const string WIA_VERTICAL_SCAN_SIZE_PIXELS = "6152";
const string WIA_SCAN_BRIGHTNESS_PERCENTS = "6154";
const string WIA_SCAN_CONTRAST_PERCENTS = "6155";
SetWIAProperty(scannnerItem.Properties, WIA_HORIZONTAL_SCAN_RESOLUTION_DPI, scanResolutionDPI);
SetWIAProperty(scannnerItem.Properties, WIA_VERTICAL_SCAN_RESOLUTION_DPI, scanResolutionDPI);
SetWIAProperty(scannnerItem.Properties, WIA_HORIZONTAL_SCAN_START_PIXEL, scanStartLeftPixel);
SetWIAProperty(scannnerItem.Properties, WIA_VERTICAL_SCAN_START_PIXEL, scanStartTopPixel);
SetWIAProperty(scannnerItem.Properties, WIA_HORIZONTAL_SCAN_SIZE_PIXELS, scanWidthPixels);
SetWIAProperty(scannnerItem.Properties, WIA_VERTICAL_SCAN_SIZE_PIXELS, scanHeightPixels);
SetWIAProperty(scannnerItem.Properties, WIA_SCAN_BRIGHTNESS_PERCENTS, brightnessPercents);
SetWIAProperty(scannnerItem.Properties, WIA_SCAN_CONTRAST_PERCENTS, contrastPercents);
SetWIAProperty(scannnerItem.Properties, WIA_SCAN_COLOR_MODE, colorMode);
}
}
}
Then see below the .cs file of the form named Form1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
namespace TESTSCAN
{
public partial class Form1 : Form
{
int cropX, cropY, cropWidth, cropHeight;
//here rectangle border pen color=red and size=2;
Pen borderpen = new Pen(Color.Red, 2);
Image _orgImage;
Bitmap crop;
List<string> devices;
//fill the rectangle color =white
SolidBrush rectbrush = new SolidBrush(Color.FromArgb(100, Color.White));
int pages;
int currentPage = 0;
public Form1()
{
InitializeComponent();
IsSaved = false;
}
List<Image> images;
private string f_path;
private string doc_no;
private bool savedOrNot = false;
private List<string> fNames;
public List<string> fileNames
{
get { return fNames; }
set { fNames = value; }
}
public String SavePath
{
get { return f_path; }
set { f_path = value; }
}
public String DocNo
{
get { return doc_no; }
set { doc_no = value; }
}
public bool IsSaved
{
get { return savedOrNot; }
set { savedOrNot = value; }
}
private void Form1_Load(object sender, EventArgs e)
{
lblPath.Text = SavePath;
lblDocNo.Text = DocNo;
//get list of devices available
devices = WIAScanner.GetDevices();
foreach (string device in devices)
{
lbDevices.Items.Add(device);
}
//check if device is not available
if (lbDevices.Items.Count != 0)
{
lbDevices.SelectedIndex = 0;
}
}
private void btnPreview_Click(object sender, EventArgs e)
{
try
{
//get list of devices available
if (lbDevices.Items.Count == 0)
{
MessageBox.Show("You do not have any WIA devices.");
}
else
{
//get images from scanner
pages =3;
images = WIAScanner.Scan((string)lbDevices.SelectedItem, pages);
pages = images.Count;
if (images != null)
{
foreach (Image image in images)
{
pic_scan.Image = images[0];
pic_scan.Show();
pic_scan.SizeMode = PictureBoxSizeMode.StretchImage;
_orgImage = images[0];
crop = new Bitmap(images[0]);
btnOriginal.Enabled = true;
btnSave.Enabled = true;
currentPage = 0;
//pic_scan.Image = image;
//pic_scan.Show();
//pic_scan.SizeMode = PictureBoxSizeMode.StretchImage;
//_orgImage = image;
//crop = new Bitmap(image);
//btnOriginal.Enabled = true;
//btnSave.Enabled = true;
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
List<string> sss = new List<string>();
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (crop != null)
{
SavePath = #"D:\NAJEEB\scanned images\";
DocNo = "4444";
string currentFName = DocNo + Convert.ToString(currentPage + 1) + ".jpeg";
crop.Save(SavePath + currentFName, ImageFormat.Jpeg);
sss.Add(currentFName);
MessageBox.Show("Document Saved Successfully");
IsSaved = true;
currentPage += 1;
if (currentPage < (pages))
{
pic_scan.Image = images[currentPage];
pic_scan.Show();
pic_scan.SizeMode = PictureBoxSizeMode.StretchImage;
_orgImage = images[currentPage];
crop = new Bitmap(images[currentPage]);
btnOriginal.Enabled = true;
btnSave.Enabled = true;
}
else
{ btnSave.Enabled =false;
fileNames = sss;
}
}
}
catch (Exception exc)
{
IsSaved = false;
MessageBox.Show(exc.Message);
}
}
private void btnOriginal_Click(object sender, EventArgs e)
{
if (_orgImage != null)
{
crop = new Bitmap(_orgImage);
pic_scan.Image = _orgImage;
pic_scan.SizeMode = PictureBoxSizeMode.StretchImage;
pic_scan.Refresh();
}
}
private void pic_scan_MouseDown(object sender, MouseEventArgs e)
{
try
{
if (e.Button == MouseButtons.Left)//here i have use mouse click left button only
{
pic_scan.Refresh();
cropX = e.X;
cropY = e.Y;
Cursor = Cursors.Cross;
}
pic_scan.Refresh();
}
catch { }
}
private void pic_scan_MouseMove(object sender, MouseEventArgs e)
{
try
{
if (pic_scan.Image == null)
return;
if (e.Button == MouseButtons.Left)//here i have use mouse click left button only
{
pic_scan.Refresh();
cropWidth = e.X - cropX;
cropHeight = e.Y - cropY;
}
pic_scan.Refresh();
}
catch { }
}
private void pic_scan_MouseUp(object sender, MouseEventArgs e)
{
try
{
Cursor = Cursors.Default;
if (cropWidth < 1)
{
return;
}
Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
Bitmap bit = new Bitmap(pic_scan.Image, pic_scan.Width, pic_scan.Height);
crop = new Bitmap(cropWidth, cropHeight);
Graphics gfx = Graphics.FromImage(crop);
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;//here add System.Drawing.Drawing2D namespace;
gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;//here add System.Drawing.Drawing2D namespace;
gfx.CompositingQuality = CompositingQuality.HighQuality;//here add System.Drawing.Drawing2D namespace;
gfx.DrawImage(bit, 0, 0, rect, GraphicsUnit.Pixel);
}
catch { }
}
private void pic_scan_Paint(object sender, PaintEventArgs e)
{
Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
Graphics gfx = e.Graphics;
gfx.DrawRectangle(borderpen, rect);
gfx.FillRectangle(rectbrush, rect);
}
}
}
Short description of the working flow:
On form load event the available scanner devices adding to drop down list.
The user can select any device from this drop down.
On Preview button click, the document is scanned to application and is shown in the picture box.
There is another picture box in the form for keeping the cropped image. If you select any area from the picture in the picture box then you will feel the cropping effect. The cropped image keep in the second picture box placed behind the first picture box.
On save button click the image save into the specified location in the disk.
This location we can configure from the application. See the code.

Rotate Image and View Next Page

I’m using WinForms for my application. I’m building an image viewer. My application opens image documents (.tif) files. The application has the ability to go to the next page.
The issue is, that every time I try to rotate the image and click next, the image stays on the same page but the page number increments.
Why can’t I see the images when it’s on rotate?
How can I rotate the image and go to the next page?
In the link below I've provided a test tif document for testing purposes:
http://www.filedropper.com/sampletifdocument5pages
My Code:
FileStream _stream;
Image _myImg; // setting the selected tiff
string _fileName;
private int intCurrPage = 0; // defining the current page
private int intTotalPages = 0;
private void Open_Btn_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
lblFile.Text = openFileDialog1.FileName;
// Before loading you should check the file type is an image
if (_myImg == null)
{
_fileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
File.Copy(#lblFile.Text, _fileName);
_stream = new FileStream(_fileName, FileMode.Open, FileAccess.Read);
pictureBox1.Image = Image.FromStream(_stream);
}
//pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
pictureBox1.Size = new Size(750, 1100);
// Reset the current page when loading a new image.
intCurrPage = 1;
intTotalPages = pictureBox1.Image.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
lblNumPages.Text = intTotalPages.ToString();
lblCurrPage.Text = "1";
}
}
private void NextPage_btn_Click(object sender, EventArgs e)
{
if (intCurrPage <= (intTotalPages - 1))
{
if(Radio_90_Rotate.Checked)
{
pictureBox1.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
if(Radio_180_Rotate.Checked)
{
pictureBox1.Image.RotateFlip(RotateFlipType.Rotate180FlipNone);
}
// Directly increment the active frame within the image already in the PictureBox
pictureBox1.Image.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, intCurrPage);
//page increment (Go to next page)
intCurrPage++;
// Refresh the PictureBox so that it will show the currently active frame
pictureBox1.Refresh();
lblCurrPage.Text = intCurrPage.ToString();
}
}
The RotateFlip function will change the source image and flatten it to only one page. This means we need to make copies each time you view a new page that has rotation applied.
In this solution, I use the source image and simply change pages when no rotation is applied. But when rotation is set, then a Image copy is made for each page and then the rotation is applied to the copy only.
Using your sample image it takes time to load each page. So I implemented a simple label message to let the user know it's working.
Also, you may consider looking into classes prebuilt for tiff files like: https://bitmiracle.github.io/libtiff.net/
private Image _Source = null;
private int _TotalPages = 0;
private int _CurrentPage = 0;
private void Frm_TiffViewer_Load(object sender, EventArgs e)
{
lbl_WaitMessage.Visible = false;
// These two options can be adjusted as needed and probably should be set in the form control properties directly:
pictureBox1.Size = new Size(750, 1100);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void ShowProcessingImageLabel()
{
lbl_WaitMessage.Visible = true;
Application.DoEvents();
}
private void DisplayPage(int PageNumber, RotateFlipType Change)
{
if (pictureBox1.Image != null && pictureBox1.Image != _Source)
{
// Release memory for old rotated image
pictureBox1.Image.Dispose();
}
// set the variable to null for easy GC cleanup
pictureBox1.Image = null;
_Source.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, PageNumber - 1);
pictureBox1.Image = new Bitmap(_Source);
pictureBox1.Image.RotateFlip(Change);
pictureBox1.Refresh();
}
private void DisplayPage(int PageNumber)
{
ShowProcessingImageLabel();
this.lblCurrPage.Text = PageNumber.ToString();
// You could adjust the PictureBox size here for each frame OR adjust the image to fit the picturebox nicely.
if (Radio_90_Rotate.Checked == true)
{
DisplayPage(PageNumber, RotateFlipType.Rotate90FlipNone);
lbl_WaitMessage.Visible = false;
return;
}
else if (Radio_180_Rotate.Checked == true)
{
DisplayPage(PageNumber, RotateFlipType.Rotate180FlipNone);
lbl_WaitMessage.Visible = false;
return;
}
if (pictureBox1.Image != _Source)
{
if (pictureBox1.Image != null)
{
// Release memory for old copy and set the variable to null for easy GC cleanup
pictureBox1.Image.Dispose();
pictureBox1.Image = null;
}
pictureBox1.Image = _Source;
}
pictureBox1.Image.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, PageNumber-1);
pictureBox1.Refresh();
lbl_WaitMessage.Visible = false;
}
private void Open_Btn_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// Before loading you should check the file type is an image
this._Source = Image.FromFile(openFileDialog1.FileName);
_TotalPages = _Source.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
_CurrentPage = 1;
lblCurrPage.Text = "1";
lblFile.Text = openFileDialog1.FileName;
this.lblNumPages.Text = _TotalPages.ToString();
DisplayPage(_CurrentPage);
}
}
private void NextPage_btn_Click(object sender, EventArgs e)
{
if (_CurrentPage < _TotalPages)
{
_CurrentPage++;
}
DisplayPage(_CurrentPage);
}
private void b_Previous_Click(object sender, EventArgs e)
{
if (_CurrentPage > 1)
{
_CurrentPage--;
}
DisplayPage(_CurrentPage);
}
private void Radio_90_Rotate_CheckedChanged(object sender, EventArgs e)
{
DisplayPage(_CurrentPage);
}
private void Radio_180_Rotate_CheckedChanged(object sender, EventArgs e)
{
DisplayPage(_CurrentPage);
}
private void Radio_0_Default_CheckedChanged(object sender, EventArgs e)
{
DisplayPage(_CurrentPage);
}
I`m Created Custom Mode v3.1
public Image _Image_v3_1_CustomMode(Image b1, float angle,float dx,float dy,float sx,float sy)
{
Bitmap bitmap = new Bitmap(b1.Width, b1.Height);
using(Graphics ehack = Graphics.FromImage(bitmap))
{
ehack.RotateTransform(angle);
ehack.TranslateTransform(dx, dy);
ehack.ScaleTransform(sx, sy);
ehack.DrawImage(b1, 0, 0);
return bitmap;
}
}

How can i use a flag to draw or not to draw in the pictureBox paint event?

I have a flag in the Form1 top level: addFrame wich is set to false in the constructor.
Then in the picnt event i check if its false let me draw if its true also let me draw. The problem here is that i want to be able to draw when im running the program first time !
But when im moving the trackBar to the right i dont want it to draw anything .
private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
moveCounter++;
label6.Text = moveCounter.ToString();
if (addFrame == false)
{
WireObjectGraphics.Draw(wireObject1, g);
}
else
{
addFrame = false;
WireObjectGraphics.Draw(wireObject1, g);
}
}
This is the button click event where im clicking to set the addFrame to true:
private void button16_Click(object sender, EventArgs e)
{
wireObjectAnimation1.AddFrame();
addFrame = true;
trackBar1.Select();
}
And the scroll bar event in this case i want to make that if i move the trackBar to the right and there are no any draws already then just show the image in the pictureBox dont draw anything ! But if i move it to the right and there are already draws then do show them.
If i move it to the left allways show the previous draws.
private void trackBar1_Scroll(object sender, EventArgs e)
{
if (addFrame == false)
{
}
else
{
currentFrameIndex = trackBar1.Value - 1;
textBox1.Text = "Frame Number : " + trackBar1.Value;
wireObject1.woc.Set(wireObjectAnimation1.GetFrame(currentFrameIndex));
trackBar1.Minimum = 0;
trackBar1.Maximum = fi.Length - 1;
if (checkBox1.Checked)
{
setpicture(trackBar1.Value);
Graphics g = Graphics.FromImage(pictureBox1.Image);
g.Clear(SystemColors.Control);
pictureBox1.Invalidate();
}
else
{
setpicture(trackBar1.Value);
}
pictureBox1.Refresh();
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
button8.Enabled = false;
SaveFormPicutreBoxToBitMapIncludingDrawings(currentFrameIndex);
return;
}
}
This is the draw function in the WireObjectGraphics class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace AnimationEditor
{
class WireObjectGraphics
{
static Point connectionPointStart;
static Point connectionPointEnd;
static SolidBrush brush;
static Pen p = null;
public WireObjectGraphics()
{
}
public static void Draw(WireObject wo, Graphics graphics)
{
brush = new SolidBrush(Color.Red);
p = new Pen(brush);
Graphics g = graphics;
WireObject wireObject1 = wo;
if (wireObject1 != null)
{
for (int idx = 0; idx < wireObject1.woc.Point_X.Count; ++idx)
{
Point dPoint = new Point((int)wireObject1.woc.Point_X[idx], (int)wireObject1.woc.Point_Y[idx]);
dPoint.X = dPoint.X - 5; // was - 2
dPoint.Y = dPoint.Y - 5; // was - 2
Rectangle rect = new Rectangle(dPoint, new Size(10, 10));
g.FillEllipse(brush, rect);
// bitmapGraphics.FillEllipse(brush, rect);
// g.FillEllipse(brush, rect);
}
for (int i = 0; i < wireObject1._connectionstart.Count; i++)
{
int startIndex = wireObject1._connectionstart[i];
int endIndex = wireObject1._connectionend[i];
connectionPointStart = new Point((int)wireObject1.woc.Point_X[startIndex], (int)wireObject1.woc.Point_Y[startIndex]);
connectionPointEnd = new Point((int)wireObject1.woc.Point_X[endIndex], (int)wireObject1.woc.Point_Y[endIndex]);
p.Width = 2;
g.DrawLine(p, connectionPointStart, connectionPointEnd);
// bitmapGraphics.DrawLine(p, connectionPointStart, connectionPointEnd);
}
}
}
}
}
What i need is that first time running the program to be able to draw !
Then when moving the trackBar to the righ to check if draws already exists show them if not exist show only the image and only when i click the button it will add the draws on the frame im on.
If i move to the left allways show the draws i did in the other frames.
WireObject class:
Constructor:
class WireObject
{
private string an;
private bool fnExt;
public string lockObject;
private int idx;
public WireObjectCoordinates woc;
private List<int> connectionStart = new List<int>();
private List<int> connectionEnd = new List<int>();
private const string version = "01.00";
string wo_name;
public WireObject( string name )
{
wo_name = name;
woc = new WireObjectCoordinates();
fnExt = false;
}
In the wireobject class i have some function like connecting points(pixels) like delete pixels like save and load...
WireObjectCoordinates class is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AnimationEditor
{
class WireObjectCoordinates
{
public List<float> Point_X = new List<float>();
public List<float> Point_Y = new List<float>();
public WireObjectCoordinates()
{
}
public WireObjectCoordinates(WireObjectCoordinates w)
{
Point_X.AddRange(w.Point_X);
Point_Y.AddRange(w.Point_Y);
}
public void Set(WireObjectCoordinates w)
{
if (w == null)
{
}
else
{
for (int i = 0; i < Point_X.Count; i++)
{
Point_X[i] = w.Point_X[i];
Point_Y[i] = w.Point_Y[i];
}
}
}
}
}
The problem is still in Form1 with the flag when to show the pixels i mean when and how to call the paint event like pictureBox1.Refresh(); but oncei t will use the Draw function inside and once it will not. When i run the program let me use the draw function once i moved the trackBar to the right dont use the draw function.
For a windows form control OnPaint is only called when a.) a window overlapping the current control is moved out of the way OR b.) you manually invalidate the control : http://msdn.microsoft.com/en-us/library/1e430ef4.aspx
So OnPaint should be getting called too often.

Sprites and C# animation

I found a class to make a gif file containing multiple frame animations run in front of a background image. This is my class:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace AnimSprites {
public class AnimSprite {
private int frame, interval, width, height;
private string imgFile;
private Image img;
private Timer frameTimer;
public AnimSprite(string f_imgFile, int f_width) {
frame = 0;
width = f_width;
imgFile = f_imgFile;
img = new Bitmap(imgFile);
height = img.Height;
}
public void Start(int f_interval) {
interval = f_interval;
frameTimer = new Timer();
frameTimer.Interval = interval;
frameTimer.Tick += new EventHandler(advanceFrame);
frameTimer.Start();
}
public void Start() {
Start(100);
}
public void Stop() {
frameTimer.Stop();
frameTimer.Dispose();
}
public Bitmap Paint(Graphics e) {
Bitmap temp;
Graphics tempGraphics;
temp = new Bitmap(width, height, e);
tempGraphics = Graphics.FromImage(temp);
tempGraphics.DrawImageUnscaled(img, 0-(width*frame), 0);
tempGraphics.Dispose();
return(temp);
}
private void advanceFrame(Object sender, EventArgs e) {
frame++;
if ( frame >= img.Width/width )
frame = 0;
}
}
}
How can I use this class to make my gif file (running_dog.gif) run over background.jpg from left to right?
This is the dog.gif file: dog.gif
The class you've included expects the animation frames to go from left to right rather than top to bottom as your .gif does.
You can alter it by changing the constructor to
public AnimSprite(string f_imgFile, int f_height) {
frame = 0;
height = f_height;
imgFile = f_imgFile;
img = new Bitmap(imgFile);
width = img.Width;
}
and the advanceFrame method to
private void advanceFrame(Object sender, EventArgs e) {
frame++;
if ( frame >= img.Height/height )
frame = 0;
}
}
and your call to DrawImageUnscaled to
tempGraphics.DrawImageUnscaled(img, 0, 0-(height*frame));

Categories

Resources