Okay, so i am working in xna and i want to open this textfile which should open in a textfile. Here is the code:
if (Keyboard.GetState().IsKeyDown(Keys.G) == true)
{
var fileToOpen = "Name.txt";
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
UseShellExecute = true,
FileName = fileToOpen
};
process.Start();
process.WaitForExit();
}
However an error occurs and cant find the textfile to open. I did this in a normal consol application and just added a new item textfile to the project and it worked fine in the console application, however in XNA it does not seem to work at all.
Also im really not well educated in file directory things and need a quick fix. The text files are placed in this area:
I hope this is of somehelp im trying to give as much information as possible. Just to note streamwriting to textfiles in the directory location shown in the image link works perfectly fine and i just give the name of the file as shown below:
if (player.GetRec.Intersects(map.sharkRec))
{
using (StreamWriter writer = new StreamWriter("CurrentScore.txt"))
{
writer.Write(time);
}
player.Position = new Vector2(64,100);
mCurrentScreen = ScreenState.leaderboard;
}
However it just didt seem to work when i want to open the textfile in notepad and allow for typing to be done in the textfile in notepad. The reason why i want to open a text file for typing is the user entering there name and i dont have knowledge or the time to do XNA textbox input creation which seems complicated from the tutorials i have seen, which is why i want to open the textfile in notepad for editing. Furthermore this is going to be used on other people's computers so if directorys have to be used i need a directory that will work on other computers as well as my own, just to note directory entering seems to confuse me.
Hope i have given enough information and i really hope someone can help this beginner out here :)
For this to work, your code should be something like this:
using(StreamWriter ...)
{
show textbox so the user can see what he's typing
for each keypress add the letter
exit on ESC button (for example)
delete char on Backspace
etc...
}
Now, I personaly don't recommend this type of code. Open the file, do what you have to do with it and close it. The code below is how I programmed textbox for my game. I hope it helps (you could say this is more a little tutoial for better approach to the problem instead an answer to the exact problem you put up for yourself).
namespace Acircalipse.MenuClasses
{
public class TextBox:MenuItem
{
private string originTitle;
public string Text
{
get
{
return title.Replace(originTitle, "").Replace(Menu.separator, "");
}
}
public int index, max;
public TextBox (string Title, string text = "", int MaxCharacters = 14)
{
originTitle = Title;
index = 0;
max = MaxCharacters;
SetText(text);
}
public void SetText (string text)
{
if (text.Length > max) text = text.Substring(0, max);
title = originTitle + Menu.separator + text;
}
public void ChangeIndex (int howMuch)
{
index += howMuch;
ChangeCar(index);
}
public void AddChar (int index = 0)
{
SetText(Text + Menu.Wheel(index));
}
public void ChangeCar (int index)
{
if(Text.Length > 0)
SetText(Text.Substring(0, Text.Length - 1) + Menu.Wheel(index));
}
public void DeleteChar ()
{
if (Text.Length > 0)
SetText(Text.Substring(0, Text.Length - 1));
}
}
}
Where the Menu.Wheel(int index) is simply an array of available character for user to type in
public static char Wheel(int index)
{
string charWheel = " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int max = charWheel.Length;
while (index > max) index -= max;
while (index ("less than" sign here) 0) index += max;
return charWheel[index];
}
Where Menu.separator is a string ": ".
The code is pretty self explanatory.
Now, when using this class, you'll have to have one bool to see if the user has activated this textbox, and if he has, add text on keypress. If the textbox is inactive, just continue your normal update
What you have to understand is that textbox is a simple string witch is updated when textbox is active, and just showed when not active.
Using this simple and on point definition of TextBox, you can simply create your own class that will work the way you want to.
If this answer helped you resolve your problem, please mark it as the solution.
Related
This is going to sound really stupid, but I'm taking a class in C# where we are skipping around the book and working only from a console application. We were given an exercise to build sentences in strings based on arrays of articles, nouns, verbs, and prepositions, and capitalize the first letter in the first word of the string. The kicker is, it wants the output to a text box. That wouldn't be a problem except
a) we have bypassed all chapters regarding GUIs (that will come in the next quarter's C# class), and
b) I have checked the book and even Stack Overflow and other online sources, but couldn't figure it out.
Unfortunately, my instructor chose not to discuss this exercise in class last night. Since he and I aren't on the same page (not a dislike, more of a chemistry thing), I'm trying to figure this out on my own. And the deadline for turning this in has passed, so I'm only asking for personal edification at this point.
So, here's the code I created. I wrote it for output to a console just to show I had the basic mechanism of the problem. I know I have to create a separate form with a text box inside a GUI window, but I couldn't figure out how to send the output to a text box rather than a console.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _16._4_StoryWriter
{
class StoryWriter
{
static void Main(string[] args)
{
string[] articles = { "the", "a", "one", "some", "any" };
string[] nouns = { "boy", "girl", "dog", "town", "car" };
string[] verbs = { "drove", "jumped", "ran", "walked", "skipped" };
string[] preps = { "to", "from", "over", "under", "on" };
string articleStory = "";
string nounStory = "";
string verbStory = "";
string prepStory = "";
Random random = new Random();
for (int counter = 1; counter <= 10; ++counter)
{
int randomNext = random.Next(5);
articleStory = articles[randomNext];
randomNext = random.Next(5);
nounStory = nouns[randomNext];
randomNext = random.Next(5);
verbStory = verbs[randomNext];
randomNext = random.Next(5);
prepStory = preps[randomNext];
Console.WriteLine(UppercaseFirst(articleStory) + " " + nounStory + " " + verbStory + " " + prepStory + ".");
} // End For
Console.Read();
} // End Main
static string UppercaseFirst(string s) // Borrowed from dotnetperls.com tutorial for making first letter uppercase
{
if (string.IsNullOrEmpty(s)) // Checks for an empty string
{
return string.Empty;
}
char[] a = s.ToCharArray(); // Creates array of characters from a string
a[0] = char.ToUpper(a[0]); // Selects value of zeroth position and changes to upper case
return new string(a); // Passes new string back
} // End method
} // End Class
} // End Namespace
To create a Windows Forms Application project Start Visual Studio
2010.
On the File menu, point to New, and then select Project.
The New Project dialog box appears.
In the Installed Templates pane, expand Visual Basic or Visual C#, and
then select Windows.
Above the middle pane, select the target framework from the drop-down
list.
In the middle pane, select the Windows Forms Application template.
NoteNote The Windows Forms Application template in the .NET Framework
4 targets the Client Profile by default.
In the Name text box, specify a name for the project.
In the Location text box, specify a folder to save the project. Click
OK.
The Windows Forms Designer opens and displays Form1 of the project.
SOURCE
Then drag textbox from toolbox and place it on the form.
Double click anywhere on the form, except for textbox, which will open code behind form and you will be in form load event.
Add:
textBox1.Text = "Your text to put in textbox";
in:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "Your text to put in textbox";
}
press F5
Youtube Form
Youtube textbox
You just need a Form and a TextBox as a child of the Form:
var form = new Form{Width = 300, Height = 100, Text = "The form"};
var textbox = new TextBox{Parent=form, Size = form.ClientRectangle.Size, Multiline = true};
textbox.Text = "Your Text";
form.ShowDialog();
You'll also need this using System.Windows.Forms somewhere and reference to System.Windows.Forms.dll
I am using c# and VS2012 on a lightswitch web-application,
I wish to export my data to CSV (on a search screen!), but can't reach any POC,
As i understand there are 2 main problems - a savefiledialog must be caused directly from a user button and in it must happened in the main dispatcher,
I used this code :
partial void mySearchScreen_Created()
{
var CSVButton = this.FindControl("ExportToCSV");
CSVButton.ControlAvailable += ExportCSV_ControlAvailable;
}
private void ExportCSV_ControlAvailable(object sender, ControlAvailableEventArgs e)
{
this.FindControl("ExportToCSV").ControlAvailable -= ExportCSV_ControlAvailable;
Button Button = (Button)e.Control;
Button.Click += ExportCSV_Click;
}
private void ExportCSV_Click(object sender, System.Windows.RoutedEventArgs e)
{
Microsoft.LightSwitch.Details.Client.IScreenCollectionProperty collectionProperty = this.Details.Properties.mySearch;
var intPageSize = collectionProperty.PageSize;
//Get the Current PageSize and store to variable
collectionProperty.PageSize = 0;
var dialog = new SaveFileDialog();
dialog.Filter = "CSV (*.csv)|*.csv";
if (dialog.ShowDialog() == true) {
using (StreamWriter stream = new StreamWriter(dialog.OpenFile())) {
string csv = GetCSV();
stream.Write(csv);
stream.Close();
this.ShowMessageBox("Excel File Created Successfully. NOTE: When you open excel file and if you receive prompt about invalid format then just click yes to continue.", "Excel Export", MessageBoxOption.Ok);
}
}
collectionProperty.PageSize = intPageSize;
//Reset the Current PageSize
}
private string GetCSV()
{
StringBuilder csv = new StringBuilder();
int i = 0;
foreach (var orderRow_loopVariable in mySearch) {
var orderRow = orderRow_loopVariable;
////HEADER
if (i == 0) {
int c = 0;
foreach (var prop_loopVariable in orderRow.Details.Properties.All().OfType<Microsoft.LightSwitch.Details.IEntityStorageProperty>()) {
var prop = prop_loopVariable;
if (c > 0) {
csv.Append(",");//Constants.vbTab
}
c = c + 1;
csv.Append(prop.DisplayName);
}
}
csv.AppendLine("");
////DATA ROWS
int c1 = 0;
foreach (var prop_loopVariable in orderRow.Details.Properties.All().OfType<Microsoft.LightSwitch.Details.IEntityStorageProperty>()) {
var prop = prop_loopVariable;
if (c1 > 0) {
csv.Append(",");//Constants.vbTab
}
c1 = c1 + 1;
csv.Append(prop.Value);
}
i = i + 1;
}
if (csv.Length > 0) {
return csv.ToString(0, csv.Length - 1);
} else {
return "";
}
}
This works, but it only get's me the first page items,
On another thing i had to do i solved that problem by using this code :
this.DataWorkspace.myDataContextData.MySearch(...).Execute();
Yet trying that instead of just using 'MySearch' gives me the following error :
t is not valid to call Execute() on a different Dispatcher than the ExecutableObject's Logic Dispatcher.
Why is it so difficult to do such a basic thing related to data (export to csv/excel) on a system build for handling data ?
Any ideas ?
The simplest workaround if this is the only use of the search screen would be to turn off paging. To do this go to the screen designer, highlight the query on the left, and in properties uncheck 'support paging.'
I'm not sure what the limitations are, but you can run some code in a different dispatcher using:
this.Details.Dispatcher.BeginInvoke(() =>
{
//This runs on main dispatcher
});
I don't think there's anything wrong with your code, but I've noticed that it takes a while to reset the page size on a large collection, in which time the rest of your code continues to execute. I think that's why you only get the first page. The only solution I've found is to wait.
When the "File Download - Security Warning" dialog pops up, keep an eye on the 'busy' indicator on the screen's tab and also the 'Page x of y' status at the bottom of the grid if you can see it. Only when the busy indicator has gone and the status just says 'Page' should you click OK to continue.
I haven't figured out a way of doing this programmatically so it's not a very helpful feature unless you have a very tightly controlled user population. But if it's just you and a couple of power users, it is workable. I'm also not sure if this has been improved on in versions after VS2012.
There can be a downside to the other answer of taking the paging off the query entirely. I've tried that workaround when the grid collection was being displayed in a modal window and the window became uncloseable if there were too many rows in the grid.
Phil
I am making a program where you enter an item's name and it's description. Then you add it to a listbox and after you are done you can save all the items to a 'txt' file. (Using StreamWriter). This program also has an edit button that allows you to edit the description in the listbox by removing it first from the listbox and then showing it back in the textbox (, so you can edit it)
If the description is multi-line, it will successfuly show it multi-line when I select it in the listbox and click the edit button that will show it back in the textbox. BUT if I save all the items in the listbox to a file first. And then open up the file again so it load the items back into the listbox. And then clicking the edit button...
The multi-line description will show as a one-line description in the textbox.
I am not sure why - but I've also made a label that will show the exact string that the textbox is suppose to show and the label is showing it multi-lined while textbox isn't!
The string is definitely multi-line but the multi-line textbox is showing it one-line after loading the items back into the listbox using StreamReader.
Example of the multi-line string: (named "theString1")
This is line 1
This is line 2
Using the following code: TextBox1.Text = theString1; this appears in the text box:
This is line1This is line2
But if I use the same code with a label. It will show it correctly.
If someone can explain to me why this is happening I will be more than happy. I just need an explanation.
Thanks in advance.
---[More info]---
Just so you know. I came up with this code myself so it is probably set-up all wrong.
I will be happy if you tell me a better way to do this.
I am using a list to store the description text + the item name. I seperated these two using '`' .And splited the string (see code).
This is the code that happens when you click the edit button. It removes the item from
the listbox and shows it in the textbox so you can edit it and add to listbox again:
int index = listBox.SelectedIndex;
itemName.Text = listBox.SelectedItem.ToString();
var descVar = descList.ElementAt(index).Split('`');
string theString1 = descVar[1];
TextBox1.Text = theString1;
This is how it saves it to a file:
FileDialog save = new SaveFileDialog();
save.Title = "Save information...";
save.DefaultExt = "Text File|*.txt";
save.Filter = "Text File|*.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(save.FileName);
foreach (string s in listBox.Items) //This writes the names of item names.
{
sw.WriteLine(s);
}
sw.WriteLine("`1`"); //I use this to seperate the item names from description.
foreach (string s in descList) //This writes the descriptions that are stored in a list named "descList".
{
sw.WriteLine(s);
sw.WriteLine("``"); //I use this to seperate descriptions from each other because they are multi-line.
}
sw.WriteLine("`2`"); //Just something so I know where it ends. :D
sw.Close();
}
else
{
}
And this is how it loads: (This can definitely be better!)
FileDialog load = new OpenFileDialog();
load.Title = "Load information...";
load.DefaultExt = "Text File|*.txt";
load.Filter = "Text File|*.txt";
if (load.ShowDialog() == DialogResult.OK)
{
List<string> loadDesc = new List<string>(); //Don't ask you will see why
descList.Clear();
while (listBox.Items.Count > 0) //This removes all items in the listbox to load new ones.
{
int index = 0;
listBox.Items.RemoveAt(index);
descList.Clear();
itemName.Text = "";
}
StreamReader rw = new StreamReader(load.FileName);
for (; true; )
{
string read = rw.ReadLine();
if (read == "`1`") //When it reaches the separator I made it stops reading.
{
break;
}
else
{
listBox.Items.Add(read);
}
}
for (; true; )
{
string read = rw.ReadLine();
if (read == "`2`")
{
break;
}
else
{
loadDesc.Clear();
loadDesc.Add(read);
for (; true; ) //Please tell me if this can be done differently.
{
string read2 = rw.ReadLine();
if (read2 != "``") //This will keep reading the whole description until it reaches the separator.
{
loadDesc.Add(read2); //Adds each line into the list I created.
}
else
{
break;
}
}
string oneBigString = string.Join("\n", loadDesc); //This basically converts all strings in a list into one string.
descList.Add(oneBigString); //And this finally add the string to the main list from where it then loads.
}
}
}
else
{
}
I believe that is it.
If there is anything else you need - tell me.
string oneBigString = string.Join("\n", loadDesc); is where the issue is.
Use Environment.NewLine instead of \n
I'm also just going to go over a couple of things that could be improved with your code (there are a lot, but I just want to cover a couple).
while (listBox.Items.Count > 0) //This removes all items in the listbox to load new ones.
You don't need to iterate over every element in the listbox to remove it. You can just do listBox.clear()
Also, using break to get out of loops is generally bad practice. This should be written as...
for (; true; )
{
string read = rw.ReadLine();
if (read == "`1`") //When it reaches the separator I made it stops reading.
{
break;
}
else
{
listBox.Items.Add(read);
}
}
this
string read = rw.ReadLine()
while(read != "`1`")
{
listBox.Items.Add(read);
read = rw.ReadLine()
}
but theres more, what if 1 is never found in the file? It would crash your program, so you also need to check if there is more data to be read...
string read = rw.ReadLine()
while(read != "`1`" && !sw.EndOfStream) // Make sure you're not at the end of the file
{
listBox.Items.Add(read);
read = rw.ReadLine()
}
I want to implement something that programmatically changes the background of the text when provided with a documentline.(Something that looks very similar to a block selection of a text. I'm going to be using this for debug breakpoints of an IDE I'm designing). I don't want to have to use selection as it causes the textbox to scroll.
I think I need to make use of DocumentColorizingTransformer but I'm not 100% sure how to go about this.
public class ColorizeAvalonEdit : ICSharpCode.AvalonEdit.Rendering.DocumentColorizingTransformer
{
protected override void ColorizeLine(ICSharpCode.AvalonEdit.Document.DocumentLine line)
{
int lineStartOffset = line.Offset;
string text = CurrentContext.Document.GetText(line);
int start = 0;
int index;
if (line.LineNumber == LogicSimViewCodeWPFCtrl.currentLine)
{
while ((index = text.IndexOf(text, start)) >= 0)
{
base.ChangeLinePart(
lineStartOffset + index, // startOffset
lineStartOffset + index + text.Length, // endOffset
(VisualLineElement element) =>
{
element.TextRunProperties.SetBackgroundBrush(Brushes.Red);
});
start = index + 1; // search for next occurrence
}
}
}
}
currentLine is the portion that will be highlighted.
The above code does work properly.. only problem is if the currentLine ever changes while I am viewing that line, it doesn't highlight the updated line until I scroll to another portion of the document (hiding the updated line), and come back to the updated line.
Also, how do I make the line numbers start from zero?
Since it was their creation, I peeked at SharpDevelop's source and how they did it.
They defined a bookmark type (BreakpointBookmark) and added bookmark to the line.
bookmark itself sets the color of the line in CreateMarker method. It is strange that it is not possible to configure colors of the break-point in SharpDevelop.
Hope it helps.
protected override ITextMarker CreateMarker(ITextMarkerService markerService)
{
IDocumentLine line = this.Document.GetLine(this.LineNumber);
ITextMarker marker = markerService.Create(line.Offset, line.Length);
marker.BackgroundColor = Color.FromRgb(180, 38, 38);
marker.ForegroundColor = Colors.White;
return marker;
}
I found the answer
TxtEditCodeViewer.TextArea.TextView.Redraw();
Isn't this a duplicate of this question?
However it looks like you should call InvalidateArrange() on the editor or InvalidateVisual() on each changed visual.
I'm calling a public method from another class. It takes in a List as a parameter, and goes through the list printing out each item into a text field. The problem is the text field is remaining empty!. I've checked that the list is populated by outputing the item to the console before I put it into the text box, and the text is coming up fine there.
The list contains strings, and should output each string to the textfield followed by a semi colon.
This is the method which is being called:
public void fillAttachment(List<string> attachList)
{
for (int i = 0; i < attachList.Count; i++)
{
Console.WriteLine("List: " + attachList[i]);
txtAttach.Text += attachList[i] + ";";
}
}
I would solve it in this way:
foreach(var attach in attachList)
{
Console.WriteLine(attach);
txtAttach.AppendText(string.Format("{0};", attach));
}
Setting the text property on a text box and it not displaying could be one of the following:
You are not looking at the same control as you are setting the text in
Could you have instantiated a second copy of the form object and it is this form that you are setting the txtAttach text property in?
Could the control that you are expecting to be populated be a different one? Right click the text box that you want the text to appear in click properties and check the name.
Something else is clearing the textbox after you set it
Right click the txtAttach.Text and click Find All References, this will show you all the places that the Text property is referenced - written and read - in your project. This is a very useful way to locate other interaction with this control.
Fomatting is making the text box appear empty
Is the Font too small, or in the same colour as the background. Can you select the text in the text box?
The easiest way to test all of the above is to create a new text control on your form with a different name, change your code to populate it, check that it is indeed populated, then replace the old one.
As an aside, you could also reduce the code with a single line as follows:
public void fillAttachment(List<string> attachList)
{
txtAttach.Text = String.Join(";", attachList.ToArray());
}
Although this obviously skips out the console write line function.
Not sure why yours doesn't work but I would have done it like this...
public void fillAttachment(List<string> attachList)
{
string result = "";
//OR (if you want to append to existing textbox data)
//string result = txtAttach.Text;
for (int i = 0; i < attachList.Count; i++)
{
Console.WriteLine("List: " + attachList[i]);
result += attachList[i] + ";";
}
txtAttach.Text = result;
}
Does that work for you? If not then there is something else very wrong that is not obvious from your code