I want to play a video like that guy did [link].
I'm working on C# Windows Form Application (not NXA).
But I don't know how.
I tried using Microsoft.DirectX.AudioVideoPlayback but no luck.
This is what I tried so far :
OpenFileDialog rihanna = new OpenFileDialog();
if(rihanna.ShowDialog() == DialogResult.OK)
{
video = new Video(rihanna.FileName);
video.Owner = panel1;
video.Stop();
}
Now what can i do? I tried using video class but as I said it just did not work.
I'm able to compile but when I'm running the program, I don't see the form window.
using Microsoft.DirectX.AudioVideoPlayback;
namespace Play_Video
{
public partial class Form1 : Form
{
Video vdo;
public string mode="play";
public string PlayingPosition, Duration;
public Form1()
{
InitializeComponent();
VolumeTrackBar.Value = 4;
}
private void timer1_Tick(object sender, EventArgs e)
{
PlayingPosition = CalculateTime(vdo.CurrentPosition);
txtStatus.Text = PlayingPosition + "/" + Duration;
if (vdo.CurrentPosition >= vdo.Duration)
{
timer1.Stop();
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdo.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
else
vdoTrackBar.Value += 1;
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.Stop();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
openFileDialog1.Title = "Select video file..";
openFileDialog1.InitialDirectory = Application.StartupPath;
openFileDialog1.DefaultExt = ".avi";
openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";
if (openFileDialog1.FileName != "")
{
Form1.ActiveForm.Text = openFileDialog.FileName + " - Anand Media Player";
vdo = new Video(openFileDialog.FileName);
vdo.Owner = panel1;
panel1.Width = 700;
panel1.Height = 390;
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdoTrackBar.Minimum = 0;
vdoTrackBar.Maximum = Convert.ToInt32(vdo.Duration);
}
}
private void btnPlay_Click(object sender, EventArgs e)
{
if (vdo != null)
{
if (vdo.Playing)
{
vdo.Pause();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
}
else
{
vdo.Play();
timer1.Start();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.pause;
}
}
}
private void btnStop_Click(object sender, EventArgs e)
{
vdo.Stop();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
public string CalculateTime(double Time)
{
string mm, ss, CalculatedTime;
int h, m, s, T;
Time = Math.Round(Time);
T = Convert.ToInt32(Time);
h = (T / 3600);
T = T % 3600;
m = (T / 60);
s = T % 60;
if (m < 10)
mm = string.Format("0{0}", m);
else
mm = m.ToString();
if (s < 10)
ss = string.Format("0{0}", s);
else
ss = s.ToString();
CalculatedTime = string.Format("{0}:{1}:{2}", h, mm, ss);
return CalculatedTime;
}
private void VolumeTrackBar_Scroll(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.Audio.Volume = CalculateVolume();
}
}
public int CalculateVolume()
{
switch (VolumeTrackBar.Value)
{
case 1:
return -1500;
case 2:
return -1000;
case 3:
return -700;
case 4:
return -600;
case 5:
return -500;
case 6:
return -400;
case 7:
return -300;
case 8:
return -200;
case 9:
return -100;
case 10:
return 0;
default:
return -10000;
}
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
}
private void vdoTrackBar_Scroll(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.CurrentPosition = vdoTrackBar.Value;
}
}
private void Form1_Load(object sender, EventArgs e)
{
MaximizeBox = false;
}
private void exitToolItem_Click(object sender,EventArgs e)
{
Application.Exit();
}
}
}
Okey Namespace is clear:
using Microsoft.DirectX.AudioVideoPlayback;
Some Global Variables in Form:
Video vdo;
public string mode="play";
public string PlayingPosition, Duration;
And now in your Button or what else to open:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
openFileDialog1.Title = "Select video file..";
openFileDialog1.InitialDirectory = Application.StartupPath;
openFileDialog1.DefaultExt = ".avi";
openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";
vdo = new Video(openFileDialog.FileName);
vdo.Owner = panel1;
panel1.Width = 700;
panel1.Height = 390;
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdoTrackBar.Minimum = 0;
vdoTrackBar.Maximum = Convert.ToInt32(vdo.Duration);
And in some other Button Code to Start/Pause:
if (vdo.Playing)
{
vdo.Pause();
btnPlay.Text= "Play";
}
else
{
vdo.Play();
btnPlay.Text= "Pause";
}
BTW:
Don't name variables/members or something else in your Code after Girls...
If your aren't sure how to name it, there are some Guidelines here.
The goal is to provide a consistent set of naming
conventions that results in names that make immediate sense to
developers.
For AudioVideoPlayback to work, you'll need to add the AudioVideoPlayback reference, with Reference > Add Reference > Browse > C: > Windows > Microsoft.Net > DirectX for managed code > 1.0.2902.0 > Microsoft.DirectX.AudioVideoPlayback.dll
Related
This is a simple calculator program I am trying to make using Windows Forms Application in VS. The UnhandledException appears when I click anywhere except on the calculator buttons. I am fairly new to C# and it seems that a sender button in my function "common_operators" is causing the exception. Also, I want this calculator to have similar memory functionalities as windows 10's built-in calculator. I've searched everywhere but couldn't find a c# calculator implementation that is similar to Win10's built-in calculator has, I have already started but I think there's a better way to implement it. If u need more info, I've uploaded the "designer.cs" file that relates to the form application.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp_Calculator;
namespace WindowsFormsApp_Calculator
{
public partial class CalculatorBase : Form
{
public double[] arrMemory = new double[5];
public int indexer = 0;
double result = 0;
string asmd_operator = ""; // ASMD - Addition, Subtraction, Multiplication, Division
bool insert_value = false;
public CalculatorBase()
{
InitializeComponent();
btn_mc.Enabled = false;
btn_mr.Enabled = false;
mem_textbox.Text = "There's nothing saved in memory";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void numbers_zerotonine(object sender, EventArgs e)
{
Button b = (Button)sender;
if((box_display.Text == "0") || insert_value)
box_display.Text = "";
insert_value = false;
box_display.Text = box_display.Text + b.Text;
}
private void common_operators(object sender, EventArgs e)
{
Button b = (Button)sender;
if (result != 0)
{
btn_eql.PerformClick();
insert_value = true;
asmd_operator = b.Text;
subbox_display.Text = result + " " + asmd_operator;
}
else
{
asmd_operator = b.Text;
result = double.Parse(box_display.Text);
box_display.Text = "";
subbox_display.Text = System.Convert.ToString(result) + " " + asmd_operator;
}
}
private void btn_ce_Click(object sender, EventArgs e)
{
box_display.Text = "0";
}
private void btn_c_Click(object sender, EventArgs e)
{
box_display.Text = "0";
subbox_display.Text = "";
result = 0;
}
private void btn_eql_Click(object sender, EventArgs e)
{
subbox_display.Text = "";
switch(asmd_operator)
{
case "-":
box_display.Text = (result - double.Parse(box_display.Text)).ToString();
break;
case "+":
box_display.Text = (result + double.Parse(box_display.Text)).ToString();
break;
case "X":
box_display.Text = (result * double.Parse(box_display.Text)).ToString();
break;
case "/":
box_display.Text = (result / double.Parse(box_display.Text)).ToString();
break;
default:
break;
}
result = double.Parse(box_display.Text);
asmd_operator = "";
}
private void btn_bs_Click(object sender, EventArgs e)
{
if(box_display.Text.Length > 0)
{
box_display.Text = box_display.Text.Remove(box_display.Text.Length - 1, 1);
}
if(box_display.Text == "")
{
box_display.Text = "0";
}
}
private void btn_ms_Click(object sender, EventArgs e)
{
if (indexer == 5)
{
mem_textbox.Text = "Memory is full. Max limit = 5";
}
else
{
int hgt = 75;
mem_textbox.Text = "";
arrMemory[indexer] = double.Parse(box_display.Text);
indexer++;
btn_mc.Enabled = true;
btn_mr.Enabled = true;
TextBox mem = new TextBox();
mem.Multiline = true;
mem.TextAlign = HorizontalAlignment.Right;
mem.Width = 275;
mem.Height = 70;
mem.Font = new Font(mem.Font.FontFamily, 20);
mem.Text = box_display.Text;
mem.Location = new Point(387, hgt);
this.Controls.Add(mem);
}
}
private void btn_mc_Click(object sender, EventArgs e)
{
foreach (int i in arrMemory)
{
arrMemory[i] = 0;
}
indexer = 0;
btn_mr.Enabled = false;
btn_mc.Enabled = false;
mem_textbox.Text = "There's nothing saved in memory";
}
private void btn_mr_Click(object sender, EventArgs e)
{
box_display.Text = arrMemory[indexer].ToString();
}
private void btn_mp_Click(object sender, EventArgs e)
{
arrMemory[indexer] += double.Parse(box_display.Text);
}
private void btn_mm_Click(object sender, EventArgs e)
{
arrMemory[indexer] -= double.Parse(box_display.Text);
}
}
}
From your designer.cs you've got a Click event handler on the form itself that invokes common_operators, so if that gets fired, it will be an invalid cast since sender will be your CalculatorBase form type and not Button
This question already has an answer here:
Interaction between forms — How to change a control of a form from another form?
(1 answer)
Closed 6 years ago.
On one Form, the Quiz form, I have an integer score which keeps track of the user's score. On another Form, the Game Over form, I need to print out the score of the user, but even after hours of me attempting to do so, I still can't manage to do it. I know my code could be improved by A LOT but I just need help to solve this problem and would appreciate it. I just started out on C# and I just wanted to experiment on things.
namespace Quiz_Application
{
public partial class Quiz : Form
{
static Random gen = new Random();
int[] rand = Enumerable.Range(1, 5).OrderBy(q => gen.Next()).ToArray();
int i = 0;
int score = 0;
int[] goArray = new int[1];
public void Question1()
{
questionText.Text = "What is the capital city of Spain?";
optionA.Text = "Barcelona";
optionB.Text = "Madrid";
optionC.Text = "Seville";
optionD.Text = "Zarazoga";
}
public void Question2()
{
questionText.Text = "What is the biggest island on Earth?";
optionA.Text = "Luzon";
optionB.Text = "Singapore";
optionC.Text = "Greenland";
optionD.Text = "Hawaii";
}
public void Question3()
{
questionText.Text = "What is the world's longest river?";
optionA.Text = "Nile";
optionB.Text = "Amazon";
optionC.Text = "Mississipi";
optionD.Text = "Congo";
}
public void Question4()
{
questionText.Text = "Which country is Prague in?";
optionA.Text = "Czech Republic";
optionB.Text = "Slovakia";
optionC.Text = "Austria";
optionD.Text = "Poland";
}
public void Question5()
{
questionText.Text = "What is the diameter of Earth?";
optionA.Text = "6,779km";
optionB.Text = "3,474km";
optionC.Text = "12,742km";
optionD.Text = "8,721km";
}
static void Wait(double sec)
{
Task.Delay(TimeSpan.FromSeconds(sec)).Wait();
}
public Quiz()
{
InitializeComponent();
}
private void Quiz_Load(object sender, EventArgs e)
{
}
public void label1_Click(object sender, EventArgs e)
{
scoreNum.ResetText();
score = 0;
int goScore = goArray[0];
this.Hide();
Form1 f1 = new Form1();
f1.ShowDialog();
this.Close();
}
private void optionClick(object sender, EventArgs e)
{
startButton.Enabled = false;
Button l = (Button)sender;
int[] goArray = new int[1];
goArray[0] = score;
if (l.Text == "Madrid" || l.Text == "Greenland" || l.Text == "Amazon" || l.Text == "Czech Republic" || l.Text == "12,742km")
{
score++;
scoreNum.Text = score.ToString();
correctOrWrong.Image = Resources.correct; Wait(1); correctOrWrong.Image = null;
}
else
{
correctOrWrong.Image = Resources.wrong; Wait(1); correctOrWrong.Image = null;
}
l.BackColor = System.Drawing.Color.Maroon;
optionA.Enabled = false; optionB.Enabled = false; optionC.Enabled = false; optionD.Enabled = false;
startButton.Enabled = true;
}
private void startButton_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
optionA.Enabled = true; optionB.Enabled = true; optionC.Enabled = true; optionD.Enabled = true;
if (i == 5)
{
scoreNum.ResetText();
score = 0;
int goScore = goArray[0];
b.Text = "Finish";
this.Hide();
Game_Over go = new Game_Over();
go.ShowDialog();
this.Close();
}
try
{
switch (rand[i])
{
case 1:
Question1();
i++;
break;
case 2:
Question2();
i++;
break;
case 3:
Question3();
i++;
break;
case 4:
Question4();
i++;
break;
case 5:
Question5();
i++;
break;
case 6:
Wait(2);
this.Hide();
Game_Over go = new Game_Over();
go.ShowDialog();
this.Close();
break;
}
if (i == 5)
{
b.Text = "Finish";
}
}
catch { }
if (i != 5)
b.Text = "Next";
b.Enabled = false;
}
private void mouseEnter(object sender, EventArgs e)
{
this.Cursor = Cursors.Hand;
}
private void mouseLeave(object sender, EventArgs e)
{
this.Cursor = Cursors.Default;
}
public int get(int i)
{
return i;
}
}
and my Game Over form
namespace Quiz_Application
{
public partial class Game_Over : Form
{
public Game_Over()
{
InitializeComponent();
}
private void Game_Over_Load(object sender, EventArgs e)
{
Quiz q = new Quiz();
}
private void playAgain_Click(object sender, EventArgs e)
{
Quiz q = new Quiz();
this.Hide();
q.ShowDialog();
this.Close();
}
private void mainMenu_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
this.Hide();
f1.ShowDialog();
this.Close();
}
}
Create a public class and store the value in it, you can access the value across the code.
class Globals
{
public static int Score = 0;
}
// In the window you can assign value for the variable like below
Globals.Score=<Your score>;
In the Game_Over form, add a label to display the score if you haven't done so already. I will call it myScoreLabel Then, when you show the form i.e. here:
case 6:
Wait(2);
this.Hide();
Game_Over go = new Game_Over();
go.ShowDialog();
this.Close();
break;
add this line before go.ShowDialog:
go.yourScoreLabel.Text = "Score: " + score.ToString();
I'm sorry that the title is confusing but I did not know how to ask this question; if someone can help with a better title I would appreciate it.
I am building a database of players and their match performance. The matches are displayed using a tab control, inside the matches are fields that are stored in a panel. The amount of matches goes up to 5, therefore each field is an array of size 5 to represent different values for different matches. I have ran into the problem of trying to save the amount of tabs (matches) there are for that unique player.
Because the amount of tabs carries over to the next player shown, I tried to iterate through all the matches and all the fields for that player, determine which matches contain empty fields and respectively delete that tab (match). So if player 1 has 3 matches with values in fields, but player 2 only has 2 matches that contain values in fields, the 3rd match (tab) will be deleted as the fields have no values.
to better explain, this is the GUI:
Picture
My attempt at iterating through the field of each match looks like this:
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
i++;
}
However I am presented with the error: Cannot implicitly convert type 'int' to 'int[]'
I would really appriciate if someone could help me out here, I understand that the code is long but It is organised and titled so that should help.
Full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assignment1_Template2
{
public partial class Form1 : Form
{
// =======================DATA STRUCTURE ===========================
[Serializable]
private struct Player
{ //CONSTRUCTOR
public Player(int noOfMatches)
{
uniquePlayerId = new int[noOfMatches];
playerIgName = "";
contactStreet = "";
contactTown = "";
contactPostcode = "";
contactEmail = "";
contactTelephone = "";
imagePath = "";
matchesCount = 0;
csNumber = new int[noOfMatches];
killsNumber = new int[noOfMatches];
deathsNumber = new int[noOfMatches];
assistsNumber = new int[noOfMatches];
minutesNumber = new int[noOfMatches];
for (int i = 0; i < noOfMatches; ++i)
{
uniquePlayerId[i] = 0;
csNumber[i] = 0;
killsNumber[i] = 0;
deathsNumber[i] = 0;
assistsNumber[i] = 0;
minutesNumber[i] = 0;
}
}
//DATA TYPES
public int[] uniquePlayerId;
public int[] csNumber;
public int[] killsNumber;
public int[] deathsNumber;
public int[] assistsNumber;
public int[] minutesNumber;
public int matchesCount;
public string playerIgName;
public string contactStreet;
public string contactTown;
public string contactPostcode;
public string contactEmail;
public string contactTelephone;
public string imagePath;
}
//GLOBAL VARIABLES
public ArrayList GameDB;
public ArrayList playerMatch;
private int currentEntryShown = 0;
private int numberOfEntries = 0;
private string filename = "W:\\test.dat";
public string prevImage = "";
// =========================================================================
// ====================== STARTING POINT ===================================
// =========================================================================
public Form1()
{
InitializeComponent();
GameDB = new ArrayList();
LoadData();
ShowData();
UpdatePrevNextBtnStatus();
}
// =========================================================================
// ========================= BUTTON ACTION HANDLERS ========================
// =========================================================================
private void showPreviousBtn_Click(object sender, EventArgs e)
{
--currentEntryShown;
ShowData();
UpdatePrevNextBtnStatus();
}
private void showNextBtn_Click(object sender, EventArgs e)
{
++currentEntryShown;
if (currentEntryShown < GameDB.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void addNewPlayerBtn_Click(object sender, EventArgs e)
{
++numberOfEntries;
currentEntryShown = numberOfEntries - 1;
Player aNewStruct = new Player(5);
GameDB.Add(aNewStruct);
ShowData();
addNewPlayerBtn.Enabled = true;
UpdatePrevNextBtnStatus();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
SaveData();
addNewPlayerBtn.Enabled = true;
UpdatePrevNextBtnStatus();
}
private void deletePlayerBtn_Click(object sender, EventArgs e)
{
numberOfEntries--;
GameDB.RemoveAt(currentEntryShown);
SaveData();
currentEntryShown--;
if (currentEntryShown <= GameDB.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.Title = "Select an image file";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.imagePath = openFileDialog1.FileName;
GameDB[currentEntryShown] = aNewStruct;
playerPictureBox.ImageLocation = openFileDialog1.FileName;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void searchBtn_Click(object sender, EventArgs e)
{
string toFind;
string source;
toFind = searchInput.Text;
toFind = toFind.ToLower();
for (int i = 0; i < GameDB.Count; ++i)
{
source = ((Player)GameDB[i]).playerIgName + ((Player)GameDB[i]).contactStreet;
source = source.ToLower();
if (source.Contains(toFind))
{
currentEntryShown = i;
ShowData();
UpdatePrevNextBtnStatus();
break;
}
if (i == (GameDB.Count - 1))
{
MessageBox.Show(toFind + " not found");
}
}
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveData();
UpdatePrevNextBtnStatus();
}
private void addNewMatchBtn_Click(object sender, EventArgs e)
{
TabPage newTP = new TabPage();
if (tabMatches.TabCount <= 4)
{
tabMatches.TabPages.Add(newTP);
int TabPageNumber = tabMatches.SelectedIndex + 1;
tabMatches.TabPages[TabPageNumber].Text = "Match " + (TabPageNumber + 1);
tabMatches.SelectTab(TabPageNumber);
deleteMatchBtn.Enabled = true;
panel1.Parent = tabMatches.SelectedTab;
}
ShowData();
}
private void deleteMatchBtn_Click(object sender, EventArgs e)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
int lastTabNumber = tabMatches.TabCount - 1;
tabMatches.SelectTab(lastTabNumber);
if (tabMatches.SelectedIndex < 1) deleteMatchBtn.Enabled = false;
}
// =========================================================================
// ================ HANDLE DATA CHANGES BY USER ============================
// =========================================================================
private void playerIdBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
GameDB[currentEntryShown] = aNewStruct;
}
private void playerIgNameBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.playerIgName = playerIgNameBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactStreetBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactStreet = contactStreetBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactTownBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactTown = contactTownBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactPostcode = contactPostcodeBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactEmailBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactEmail = contactEmailBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.contactTelephone = contactTelephoneBox.Text;
GameDB[currentEntryShown] = aNewStruct;
}
//Match data
private void tabMatches_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Parent = tabMatches.SelectedTab;
ShowData();
}
private void numCS_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.csNumber[tabMatches.SelectedIndex] = (int)numCS.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numKills_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.killsNumber[tabMatches.SelectedIndex] = (int)numKills.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numDeaths_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.deathsNumber[tabMatches.SelectedIndex] = (int)numDeaths.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numAssists_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.assistsNumber[tabMatches.SelectedIndex] = (int)numAssists.Value;
GameDB[currentEntryShown] = aNewStruct;
}
private void numMinutes_ValueChanged(object sender, EventArgs e)
{
Player aNewStruct = new Player(5);
aNewStruct = (Player)GameDB[currentEntryShown];
aNewStruct.minutesNumber[tabMatches.SelectedIndex] = (int)numMinutes.Value;
GameDB[currentEntryShown] = aNewStruct;
}
// =========================================================================
// ================= HELPER METHODS FOR DISPLAYING DATA ====================
// =========================================================================
private void ShowData()
{
playerIdBox.Text = ((Player)GameDB[currentEntryShown]).uniquePlayerId[0].ToString();
playerIgNameBox.Text = ((Player)GameDB[currentEntryShown]).playerIgName;
contactStreetBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactStreet;
contactTownBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactTown;
contactPostcodeBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactPostcode;
contactEmailBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactEmail;
contactTelephoneBox.Text = "" + ((Player)GameDB[currentEntryShown]).contactTelephone;
playerPictureBox.ImageLocation = ((Player)GameDB[currentEntryShown]).imagePath;
numCS.Value = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
numKills.Value = ((Player)GameDB[currentEntryShown]).killsNumber[tabMatches.SelectedIndex];
numDeaths.Value = ((Player)GameDB[currentEntryShown]).deathsNumber[tabMatches.SelectedIndex];
numAssists.Value = ((Player)GameDB[currentEntryShown]).assistsNumber[tabMatches.SelectedIndex];
numMinutes.Value = ((Player)GameDB[currentEntryShown]).killsNumber[tabMatches.SelectedIndex];
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
}
private void UpdatePrevNextBtnStatus()
{
if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
else showPreviousBtn.Enabled = false;
if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
else showNextBtn.Enabled = false;
label1.Text = "Player ID";
label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
}
// =========================================================================
// =============== HELPER METHODS FOR LOADING AND SAVING ===================
// =========================================================================
private void SaveData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, GameDB);
MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Could not serialise to " + filename,
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
MessageBox.Show("Could not open " + filename +
" for saving.\nNo access rights to the folder, perhaps?",
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void LoadData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
try
{
BinaryFormatter bf = new BinaryFormatter();
GameDB = (ArrayList)bf.Deserialize(fs);
currentEntryShown = 0;
numberOfEntries = GameDB.Count;
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename +
"\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
"FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
fs.Close();
Environment.Exit(1);
}
fs.Close();
}
catch
{
if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
"FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
Player aNewStruct = new Player(5);
GameDB.Add(aNewStruct);
numberOfEntries = 1;
currentEntryShown = 0;
}
}
}
// =========================================================================
// ====================== HELPER METHODS FOR SORTING =======================
// =========================================================================
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
GameDB.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Player)x).playerIgName.CompareTo(((Player)y).playerIgName);
}
}
// =========================================================================
// ====================== MISC STUFF =======================================
// =========================================================================
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void developerToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("By Szymon Zmudzki: 13042432");
}
}
}
Try change this
int[] csNumberTF = ((Player)GameDB[currentEntryShown]).csNumber[tabMatches.SelectedIndex];
int i = 0;
while (i < 5)
{
if (csNumberTF[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
To use the csNumber which is int[] in the for loop
int i = 0;
while (i < 5)
{
if (((Player)GameDB[currentEntryShown]).csNumber[i] == 0)
{
int tabsLeft = tabMatches.TabCount;
if(tabsLeft > 1)
{
tabMatches.TabPages.Remove(tabMatches.SelectedTab);
tabsLeft--;
}
}
i++;
}
To find out the value of tabMatches.TabCount, add this line when you run the program and see it in the output window: (To answer your question, I would assume the TabCount start with 1. That's the default value of any .Count() call to an array of integer. But this is the best way to know for sure.)
System.Diagnostics.Debug.WriteLine(tabMatches.TabCount);
The Code is given below. it receives filepaths in a list from Form1 and then whole transformation takes place here and everything is working fine BUT the PROBLEM is that progressbar1 does not progress.. what could be the reason? Thanks in advance!
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
numericUpDown1.Enabled = false;
numericUpDown2.Enabled = false;
button1.Enabled = false;
}
List<string> filepath_ = new List<string>();
int count = 0, total = 0;
private string format = string.Empty;
private int _height = 0;
private int _width = 0;
internal void passpath(List<string> fp)
{
filepath_.AddRange(fp);
total = filepath_.Count;
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Stop")
{
backgroundWorker1.CancelAsync();
button1.Text = "Transform";
return;
}
else
{
button1.Text = "Stop";
System.Threading.Thread.Sleep(1);
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
foreach (string filepath in filepath_)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
ImageFormat imageFormat = ImageFormat.Jpeg;
switch (format)
{
case "JPEG":
imageFormat = ImageFormat.Jpeg;
break;
break;
default:
break;
}
string finalpath = filepath.Substring(0, filepath.IndexOf('.'));
Image image1 = Image.FromFile(filepath);
string ext = Path.GetExtension(filepath);
if (_height != 0 && _width != 0 && format!=string.Empty)
{
Bitmap bitmap = new Bitmap(image1, _width, _height);
bitmap.Save(finalpath + " (" + _width.ToString() + "x" + _height.ToString() + ")." +format, imageFormat);
}
else if (_height != 0 && _width != 0)
{
Bitmap bitmap = new Bitmap(image1, _width, _height);
bitmap.Save(finalpath + " (" + _width.ToString() + "x" + _height.ToString() + ")" + ext);
}
else if (format != string.Empty)
{
Bitmap bitmap = new Bitmap(image1);
bitmap.Save(finalpath+"." + format, imageFormat);
}
count++;
int i = ((count / total) * 100);
backgroundWorker1.ReportProgress(i);
System.Threading.Thread.Sleep(1);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label6.Text = count.ToString() + " Out of " + total.ToString() + " Images transformed";
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Text = "Transform";
progressBar1.Value = 0;
if (e.Cancelled)
MessageBox.Show("Transformation stopped. " + count.ToString() + " images transformed.");
else if (e.Error != null)
MessageBox.Show(e.Error.Message);
else
{
MessageBox.Show(count.ToString() + " Images Transformed");
Application.Exit();
}
}
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
format = ((ListBox)sender).SelectedItem.ToString();
button1.Enabled = true;
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
_width = 640;
_height = 480;
button1.Enabled = true;
}
}
}
}
Change you variables to doubles:
double count = 0, total = 0;
When you do this calculation:
int i = ((count / total) * 100);
You're currently doing integer arithmetic. The result of count / total (i.e 1 / 10 or 4 / 10) is rounded to 0. When you divide that by 100, the result is still 0, so your ProgressBar won't move.
Using the double type will correctly store the fractional part of your quotient.
The problem had already been pointed out by Grant Winney: It's the integer division.
Without changing data types of count and/or total you could use this:
int i = (int)((100.0 * count) / total)
or that:
int i = (100 * count) / total
where the former makes 100.0 * count a double and the division by total as well. The latter sticks to integer operations by simply multiplying count first (changing sequence of operations), such that the division will not be 0 as long as count is not 0.
pBar.Step = 2;
pBar.PerformStep();
i just made a file editor, it contains a listview and a textbox, i made that when i select and item from the list view it appears in the textbox, the text is japanese, and when i select a japanese text or line, it gives me an error: InvalidArgument: Value '0' is not valid for 'index'
can you guys help me ? this is my code:
private void Form1_Load(object sender, EventArgs e)
{
}
private void menuItem2_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
textBox1.Text = "";
menuItem12.Text = "file type is: ";
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.Filter = "All Files (*.*)|*.*";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
path = ofd.FileName;
BinaryReader br = new BinaryReader(File.OpenRead(path), Encoding.GetEncoding("SHIFT-JIS"));
foreach (char mychar in br.ReadChars(4)) menuItem12.Text += mychar;
if (menuItem12.Text != "file type is: TXTD")
{
MessageBox.Show("This is not a TXTD file...", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("File opened Succesfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
br.BaseStream.Position = 0x8;
int Pntrnum = br.ReadInt16();
menuItem11.Visible = true;
menuItem11.Text = Pntrnum.ToString();
List<int> offsets = new List<int>();
br.BaseStream.Position = 0x10;
for (int i = 0; i < Pntrnum; i++)
{
offsets.Add(br.ReadInt32());
}
Dictionary<int, string> values = new Dictionary<int, string>();
for (int i = 0; i < offsets.Count; i++)
{
int currentOffset = offsets[i];
int nextOffset = (i + 1) < offsets.Count ? offsets[i + 1] : (int)br.BaseStream.Length;
int stringLength = (nextOffset - currentOffset - 1) / 2;
br.BaseStream.Position = currentOffset;
var chars = br.ReadChars(stringLength);
values.Add(currentOffset, new String(chars));
}
foreach (int offset in offsets)
{
listView1.Items.Add(offset.ToString("X")).SubItems.Add(values[offset]);
}
br.Close();
br = null;
}
}
ofd.Dispose();
ofd = null;
}
private void menuItem4_Click(object sender, EventArgs e)
{
this.Close();
}
private void menuItem6_Click(object sender, EventArgs e)
{
BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
int number_pointers = Convert.ToInt32(menuItem11.Text);
Encoding enc = Encoding.GetEncoding("SHIFT-JIS");
bw.BaseStream.Position = 0x10;
int curr_pointer = 4 + number_pointers * 4;
for (int i = 0; i < number_pointers; i++)
{
bw.Write(curr_pointer);
curr_pointer += enc.GetByteCount(listView1.Items[i].SubItems[1].Text) + 1;
}
for (int i = 0; i < number_pointers; i++)
bw.Write(enc.GetBytes(listView1.Items[i].SubItems[1].Text + '\0'));
bw.Flush();
bw.Close();
bw = null;
}
private void menuItem8_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = Application.ExecutablePath;
sfd.Filter = "Text Files (*.txt)|*.txt";
sfd.Title = "Save Text file";
DialogResult result = sfd.ShowDialog();
if (result == DialogResult.Cancel)
return;
StreamWriter wwrite = new StreamWriter(sfd.FileName, false, Encoding.GetEncoding("SHIFT-JIS"));
for (int i = 0; i < listView1.Items.Count; ++i)
{
string Ptrs = listView1.Items[i].SubItems[0].Text;
string Strs = listView1.Items[i].SubItems[1].Text;
wwrite.WriteLine(i.ToString() + " > " + Ptrs + " > " + Strs);
}
wwrite.Close();
}
private void menuItem5_Click(object sender, EventArgs e)
{
MessageBox.Show("TXTD Editor by Omarrrio v0.1 Alpha\n2013 Copyrighted crap and whatever", "About...", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = listView1.SelectedItems[0].SubItems[1].Text;
}
private void button1_Click(object sender, EventArgs e)
{
listView1.SelectedItems[0].SubItems[1].Text = textBox1.Text;
}
private void menuItem12_Click(object sender, EventArgs e)
{
}
}
}
Before accessing the SelectedItems index, you should check if there are any items selected.
private void button1_Click(object sender, EventArgs e)
{
if(listView1.SelectedItems.Count > 0)
textBox1.Text = listView1.SelectedItems[0].SubItems[1].Text;
}
You may also want to perform a check to ensure that SubItems has an index of 1 before using it.