Can I add paper size for print (A6) - c#

I want to print full photo size A6 10*14 but my program don't have A6 size.
How I add paper size A6 in my program?
private void Printmgr_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
task = args.Request.CreatePrintTask("Print", OnPrintTaskSourceRequrested);
task.Completed += PrintTask_Completed;
task.Options.MediaSize = Windows.Graphics.Printing.PrintMediaSize.IsoA6;
PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(task.Options);
IList<string> displayedOptions = printDetailedOptions.DisplayedOptions;
// Create a new list option
PrintCustomItemListOptionDetails pageFormat = printDetailedOptions.CreateItemListOption("PageContent", "Pictures");
pageFormat.AddItem("PicturesText", "Image And Frame");
pageFormat.AddItem("PicturesOnly", "Pictures only");
// Add the custom option to the option list
displayedOptions.Add("PageContent");
printDetailedOptions.OptionChanged += printDetailedOptions_OptionChanged;
deferral.Complete();
}

If you want to print 10*14 Please set MediaSize as NorthAmerica10x14. And the size of IsoA6 is 4.13*5.83
protected override void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)
{
PrintTask printTask = null;
printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", async sourceRequestedArgs =>
{
printTask.Options.MediaSize = Windows.Graphics.Printing.PrintMediaSize.NorthAmerica10x14;
var deferral = sourceRequestedArgs.GetDeferral();
PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(printTask.Options);
IList<string> displayedOptions = printDetailedOptions.DisplayedOptions;
// Choose the printer options to be shown.
// The order in which the options are appended determines the order in which they appear in the UI
displayedOptions.Clear();
displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.Copies);
displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.Orientation);
displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.ColorMode);
// Create a new list option
PrintCustomItemListOptionDetails pageFormat = printDetailedOptions.CreateItemListOption("PageContent", "Pictures");
pageFormat.AddItem("PicturesText", "Pictures and text");
pageFormat.AddItem("PicturesOnly", "Pictures only");
pageFormat.AddItem("TextOnly", "Text only");
// Add the custom option to the option list
displayedOptions.Add("PageContent");
// Create a new toggle option "Show header".
PrintCustomToggleOptionDetails header = printDetailedOptions.CreateToggleOption("Header", "Show header");
// App tells the user some more information about what the feature means.
header.Description = "Display a header on the first page";
// Set the default value
header.TrySetValue(showHeader);
// Add the custom option to the option list
displayedOptions.Add("Header");
// Create a new list option
PrintCustomItemListOptionDetails margins = printDetailedOptions.CreateItemListOption("Margins", "Margins");
margins.AddItem("WideMargins", "Wide", "Each margin is 20% of the paper size", await wideMarginsIconTask);
margins.AddItem("ModerateMargins", "Moderate", "Each margin is 10% of the paper size", await moderateMarginsIconTask);
margins.AddItem("NarrowMargins", "Narrow", "Each margin is 5% of the paper size", await narrowMarginsIconTask);
// The default is ModerateMargins
ApplicationContentMarginTop = 0.1;
ApplicationContentMarginLeft = 0.1;
margins.TrySetValue("ModerateMargins");
// App tells the user some more information about what the feature means.
margins.Description = "The space between the content of your document and the edge of the paper";
// Add the custom option to the option list
displayedOptions.Add("Margins");
printDetailedOptions.OptionChanged += printDetailedOptions_OptionChanged;
// Print Task event handler is invoked when the print job is completed.
printTask.Completed += (s, args) =>
{
// Notify the user when the print operation fails.
if (args.Completion == PrintTaskCompletion.Failed)
{
MainPage.Current.NotifyUser("Failed to print.", NotifyType.ErrorMessage);
}
};
sourceRequestedArgs.SetSource(printDocumentSource);
deferral.Complete();
});
}
For more please refer PrintMediaSize Enum, This is official code sample

Related

Expander menu in C #

I am trying to reproduce the operation of the Control Expander WPF, or as shown in the menu of Outlook, Vertical Web Menu etc., since in WindowsForms this control does not exist. Here I leave the sample code: Menu_Expader.zip link GoogleDrive.
I have managed to do it using the following controls:
Panels
FlowLayoutPanel
1 Time Control
Button Vectors
Labels Vectors ...
This works perfectly, but it happens that to each panel I must establish a
Maximum Size and Minimum Size therefore every time I add an item inside I must modify the size of the panel where I add it, and the item are very close to each other is a bit annoying for the user's vision.
Example this is what I currently have:
EDIT
Code Sample:
// The state of an expanding or collapsing panel.
private enum ExpandState
{
Expanded,
Expanding,
Collapsing,
Collapsed,
}
// The expanding panels' current states.
private ExpandState[] ExpandStates;
// The Panels to expand and collapse.
private Panel[] ExpandPanels;
// The expand/collapse buttons.
private Button[] ExpandButtons;
// Initialize.
private void Form1_Load(object sender, EventArgs e)
{
// Initialize the arrays.
ExpandStates = new ExpandState[]
{
ExpandState.Expanded,
ExpandState.Expanded,
ExpandState.Expanded,
};
ExpandPanels = new Panel[]
{
panModule1,
panModule2,
panModule3,
};
ExpandButtons = new Button[]
{
btnExpand1,
btnExpand2,
btnExpand3,
};
// Set expander button Tag properties to give indexes
// into these arrays and display expanded images.
for (int i = 0; i < ExpandButtons.Length; i++)
{
ExpandButtons[i].Tag = i;
ExpandButtons[i].Image = Properties.Resources.expander_down;
}
}
// Start expanding.
private void btnExpander_Click(object sender, EventArgs e)
{
// Get the button.
Button btn = sender as Button;
int index = (int)btn.Tag;
// Get this panel's current expand
// state and set its new state.
ExpandState old_state = ExpandStates[index];
if ((old_state == ExpandState.Collapsed) ||
(old_state == ExpandState.Collapsing))
{
// Was collapsed/collapsing. Start expanding.
ExpandStates[index] = ExpandState.Expanding;
ExpandButtons[index].Image = Properties.Resources.expander_up;
}
else
{
// Was expanded/expanding. Start collapsing.
ExpandStates[index] = ExpandState.Collapsing;
ExpandButtons[index].Image = Properties.Resources.expander_down;
}
// Make sure the timer is enabled.
tmrExpand.Enabled = true;
}
// The number of pixels expanded per timer Tick.
private const int ExpansionPerTick = 7;
// Expand or collapse any panels that need it.
private void tmrExpand_Tick(object sender, EventArgs e)
{
// Determines whether we need more adjustments.
bool not_done = false;
for (int i = 0; i < ExpandPanels.Length; i++)
{
// See if this panel needs adjustment.
if (ExpandStates[i] == ExpandState.Expanding)
{
// Expand.
Panel pan = ExpandPanels[i];
int new_height = pan.Height + ExpansionPerTick;
if (new_height >= pan.MaximumSize.Height)
{
// This one is done.
new_height = pan.MaximumSize.Height;
}
else
{
// This one is not done.
not_done = true;
}
// Set the new height.
pan.Height = new_height;
}
else if (ExpandStates[i] == ExpandState.Collapsing)
{
// Collapse.
Panel pan = ExpandPanels[i];
int new_height = pan.Height - ExpansionPerTick;
if (new_height <= pan.MinimumSize.Height)
{
// This one is done.
new_height = pan.MinimumSize.Height;
}
else
{
// This one is not done.
not_done = true;
}
// Set the new height.
pan.Height = new_height;
}
}
// If we are done, disable the timer.
tmrExpand.Enabled = not_done;
}
I want to get a result similar to this - Bootstrap Menu Accordion:
 
Imitate that operation panels expand according to the quantity of item that it contains as long as it does not protrude from the screen, in which case it will show the scroll bar. I know there are software that provide custom controls like DVexpress, DotNetBar Suite among others, but they are Licensed Software I do not want to use it illegally pirate. Can you help me optimize it or create it in another way?
Environment: Visual Studio 2010 & .NET NetFramework 4.
The original question I made it in StackOverFlow in Spanish.
Modulo (Module)
Menu Principal (Main menu)
Mantenimientos (Maintenance)
Procesos (Processes)
Consultas (Queries)
Reportes (Reports)
Note: If someone speaks Spanish and English and can do a better translation, please edit the question. (Excuse the advertising on the image, I recorded the screen with a software trial version).

How can I save multiple user input to a spinner?

I am working with c# on Xamarin, Visual studio 2015 to develop android app. I have a box where user have to input a string value then when a button clicked, I want this value to be added to a spinner and to be saved and reloaded for the next open so he can choose the value he entered without the need to re-input it. Till now I don"t have a problem, I got my idea worked. But what I am struggling in is: if a user have input a value then clicked the button, then entered another value, only the last value is saved and showed in the spinner when the APP is re-opened. What I want is: each value entered by the user need to be saved and showed in the spinner. Then if the user want to delete the value he entered before, a button for delete item.
Here's what I have done so far:
string user;
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
var items = new List<string>() { "1", "2", "3" };
Button button4 = FindViewById<Button>(Resource.Id.button4);
Spinner spinner = FindViewById<Spinner>(Resource.Id.spinner1);
EditText input = FindViewById<EditText>(Resource.Id.input);
user = input.Text;
button4.Click += delegate
{
user = input.Text;
items.Add(user);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("try", user);
editor.Apply();
};
user = prefs.GetString("try", "no");
items.Add(user);
var adapter3 = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, items);
spinner.Adapter = adapter3;
Those code are adding and saving the user input to the spinner when I reopen the app but if the user entered two values then only the last one is saved. What I want is each value to be saved and displayed in the spinner.
Thank you in advance..
Try this:
// a constant to avoid magic strings
const string KEY_FOR_TRY = "TRY";
ArrayAdapter<string> _spinnerAdapter;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
string user;
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (this);
// Load the items from pref and fill the spinner
// if pref is empty just set an empty list.
// GetStringSet because you are loading the collection you saved.
var savedItems = prefs.GetStringSet (KEY_FOR_TRY, new List<string> ());
var items = new List<string> (savedItems);
Button button4 = FindViewById<Button> (Resource.Id.button4);
Spinner spinner = FindViewById<Spinner> (Resource.Id.spinner1);
EditText input = FindViewById<EditText> (Resource.Id.input);
user = input.Text;
button4.Click += delegate
{
//you might want validate for empty strings and if entry is already saved to prevent duplicates.
user = input.Text;
items.Add (user);
ISharedPreferencesEditor editor = prefs.Edit ();
//PutStringSet because you are saving a collection.
editor.PutStringSet (KEY_FOR_TRY, items);
editor.Apply ();
//do this only if you want to refresh the spinner values.
_spinnerAdapter.Insert (user, 0);
_spinnerAdapter.NotifyDataSetChanged ();
};
//Get the first item if there is any, don't know why you need this.
user = items.FirstOrDefault ();
_spinnerAdapter = new ArrayAdapter<string> (this, Android.Resource.Layout.SimpleSpinnerItem, items);
spinner.Adapter = _spinnerAdapter;
}
}
Hope this helps!

Set page size for WPF PrintDialog

I'm trying to print from a WPF application, but struggling to set a default page size.
The content I'm printing is supposed to be on a C5-sized envelope, and most printers here default to A4 paper.
I'd like to show a dialog to the user to allow them to choose the printer to use - but if they just press OK to accept the default printer, it defaults to A4 paper.
How can I set the print defaults for a job to C5 envelop?
Can I still prompt the user for the printer?
private void PrintVisual_Sized(UIElement toPrint)
{
PrintDialog dlg = new PrintDialog();
PrintQueue queue = dlg.PrintQueue;
// Get C5 page size if possible from printer
var availPageSizes = queue.GetPrintCapabilities().PageMediaSizeCapability;
PageMediaSize pageSize = Utilities.GetPageSize(availPageSizes, PageMediaSizeName.ISOC5Envelope);
if (pageSize != null)
{
PrintTicket ticket = new PrintTicket
{
PageMediaSize = pageSize,
InputBin = InputBin.AutoSelect,
CopyCount = 1
};
dlg.UserPageRangeEnabled = false;
var result = dlg.PrintQueue.MergeAndValidatePrintTicket(dlg.PrintTicket, ticket);
Debug.Print(result.ConflictStatus.ToString());
// Try to get the page size honoured by someone!!!
dlg.PrintQueue.DefaultPrintTicket = result.ValidatedPrintTicket;
dlg.PrintQueue.UserPrintTicket = result.ValidatedPrintTicket;
dlg.PrintTicket = result.ValidatedPrintTicket;
// Height still seems to be A4 sized!?
Debug.Print("Height: " + dlg.PrintableAreaHeight);
}
// Ask user which printer they want...
if (dlg.ShowDialog().GetValueOrDefault(false))
{
Size printSize = new Size(dlg.PrintableAreaWidth, dlg.PrintableAreaHeight);
toPrint.Measure(printSize);
toPrint.Arrange(new Rect(new Point(), printSize));
toPrint.UpdateLayout();
dlg.PrintVisual(toPrint, "My Print Job");
}
}
In the last section printSize is A4 unless the user manually selects another paper size.
Is there any way to display the dialog, with a non-default page size preset?

Resizing custom user control according to data in the webBrowser control docked in it

I have a webBrowser control named webBrowser1 that is added and docked as DockStyle.Full on a custom user control. The web-browser accepts some HTML text dynamically and displays it. I disabled the scroll bars of the webBrowser control. My problem is that whenever the content is somewhat lengthy, the webBrowser hides it from below. But the requirement of my project objective is that the webBrowser must not show either scroll bars or it should not hide some of the content. The content must be completely shown as it is without scrolling. That means the user control on which the webBrowser is docked must resize itself according to webBrowser's content. So, can anyone please suggest me how to achieve this? I searched all over the internet and SO but found nothing.
You can get the current size of HTML window via WebBrowser.Document.Window.Size and resize the container control accordingly. Depending on how your WebBrowser control content receives dynamic updates, you'd probably need to do this after each update. You could also try WebBrowser.Document.Body.ScrollRectangle if Document.Window.Size doesn't grow in the expected way.
[EDITED] The following code works for me (IE10):
private void Form1_Load(object sender, EventArgs e)
{
this.BackColor = System.Drawing.Color.DarkGray;
this.webBrowser.ScrollBarsEnabled = false;
this.webBrowser.Dock = DockStyle.None;
this.webBrowser.Location = new System.Drawing.Point(0, 0);
this.webBrowser.Size = new System.Drawing.Size(320, 200);
DownloadAsync("http://www.example.com").ContinueWith((task) =>
{
var html = task.Result;
MessageBox.Show(String.Format(
"WebBrowser.Size: {0}, Document.Window.Size: {1}, Document.Body.ScrollRectangle: {2}\n\n{3}",
this.webBrowser.Size,
this.webBrowser.Document.Window.Size,
this.webBrowser.Document.Body.ScrollRectangle.Size,
html));
this.webBrowser.Size = this.webBrowser.Document.Body.ScrollRectangle.Size;
}, TaskScheduler.FromCurrentSynchronizationContext());
}
async Task<string> DownloadAsync(string url)
{
TaskCompletionSource<bool> onloadTcs = new TaskCompletionSource<bool>();
WebBrowserDocumentCompletedEventHandler handler = null;
handler = delegate
{
this.webBrowser.DocumentCompleted -= handler;
// attach to subscribe to DOM onload event
this.webBrowser.Document.Window.AttachEventHandler("onload", delegate
{
// each navigation has its own TaskCompletionSource
if (onloadTcs.Task.IsCompleted)
return; // this should not be happening
// signal the completion of the page loading
onloadTcs.SetResult(true);
});
};
// register DocumentCompleted handler
this.webBrowser.DocumentCompleted += handler;
// Navigate to url
this.webBrowser.Navigate(url);
// continue upon onload
await onloadTcs.Task;
// the document has been fully loaded, can access DOM here
// return the current HTML snapshot
return ((dynamic)this.webBrowser.Document.DomDocument).documentElement.outerHTML.ToString();
}
To resize your usercontrol you first need to get the size needed by the content. This can be achived with TextRender.MeasureText, like so:
public static int GetContentHeight(string content, Control contentHolder, Font contentFont)
{
Font font = (contentFont != null) ? contentFont : contentHolder.Font;
Size sz = new Size(contentHolder.Width, int.MaxValue);
int padding = 3;
int borders = contentHolder.Height - contentHolder.ClientSize.Height;
TextFormatFlags flags = TextFormatFlags.WordBreak;
sz = TextRenderer.MeasureText(content, contentHolder.Font, sz, flags);
int cHeight = sz.Height + borders + padding;
return cHeight;
}
In your case it's a bit more tricky, as the text contains HTML-tags wich needs to be filtered away, to get the correct height.. I belive this can be achived with RegEx or a simple algo wich removes all content between < and > from a string.. You may also have to create special handlig for some HTML-tags (I.E Lists)

Reading to a xml file, to save new buttons, then read from that xml to show new buttons when program reloads

In my program I have eight buttons to begin with at the start (each of these representing a light in the house). The user is able to add a new button (light) to the program. I have these in a FlowLayoutPanel(FLP) and every time the program closes it saves the current state of the form, including position of the FLP its Height and Width and the current information of the buttons (including their names,text, colours etc) to an XML file.
If the FLP has it's position or size change, when the program re-loads they will be updated, like you would think and if the buttons have had something changed then they shall be updated. However, Bar the defualt eight buttons i provided, if the user adds a new button or a few, then they get saved into the xml file but the the program reloads, reading from that xml, those new buttons are discarded.
Any thoughts on this.
Current code: Reading to XML file (this is from another .cs file)
if (roomCtrl is Button)
{
xmlSerialisedForm.WriteElementString("Text", ((Button)roomCtrl).Text);
xmlSerialisedForm.WriteElementString("Backcolor",((Button)roomCtrl).BackColor.ToString());
}
if (roomCtrl is FlowLayoutPanel)
{
xmlSerialisedForm.WriteElementString("Width", ((FlowLayoutPanel)roomCtrl).Size.Width.ToString());
xmlSerialisedForm.WriteElementString("Height", ((FlowLayoutPanel)roomCtrl).Size.Height.ToString());
xmlSerialisedForm.WriteElementString("X", ((FlowLayoutPanel)roomCtrl).Location.X.ToString());
xmlSerialisedForm.WriteElementString("Y",((FlowLayoutPanel)roomCtrl).Location.Y.ToString());
}
Current code: Reading from XML file (this is from another .cs file)
case "System.Windows.Forms.Button":
if (n["Backcolor"].InnerText == "Color [LawnGreen]")
{
((System.Windows.Forms.Button)ctrlToSet).BackColor = System.Drawing.Color.LawnGreen;
}
else if (n["Backcolor"].InnerText == "Color [Tomato]")
{
((System.Windows.Forms.Button)ctrlToSet).BackColor = System.Drawing.Color.Tomato;
}
break;
case "System.Windows.Forms.FlowLayoutPanel":
((System.Windows.Forms.FlowLayoutPanel)ctrlToSet).Size = new System.Drawing.Size(Convert.ToInt32(n["Width"].InnerText), Convert.ToInt32(n["Height"].InnerText));
((System.Windows.Forms.FlowLayoutPanel)ctrlToSet).Location = new System.Drawing.Point(Convert.ToInt32(n["X"].InnerText), Convert.ToInt32(n["Y"].InnerText));
if (controlType == "System.Windows.Forms.Button")
{
Button b = new Button();
b.Name = controlName;
b.Text = n["Text"].InnerText;
if (n["Backcolor"].InnerText == "Color [LawnGreen]")
{
((System.Windows.Forms.Button)ctrlToSet).BackColor = System.Drawing.Color.LawnGreen;
{
((System.Windows.Forms.Button)ctrlToSet).BackColor = System.Drawing.Color.Tomato;
}
FlowLayoutPanel flpSockets = (FlowLayoutPanel)ctrlToSet;
flpSockets.Controls.Add(b);
}
break;
I think I'm missing something in the reading from xml file for FLP's but not sure.
Code for adding button (this is from another form)
private void button2_Click(object sender, EventArgs e)
{
if (rt.roomBool == true)
{
socket = new Button();
socket.Name = "btn"+txtSocketName.Text;
socket.Text = txtSocketName.Text;
socket.Size = new System.Drawing.Size(70, 60);
socket.BackColor = Color.LawnGreen;
rt.flpSockets.Controls.AddRange(new System.Windows.Forms.Control[] { this.socket });
rt.flpSockets.Height = 199;
rt.flpSockets.Location = new System.Drawing.Point((rt.flpSockets.Location.X), 20);
rt.Show();
}
Code for reading from the xml files destination
FormSerialisor.Serialise(this, Application.StartupPath + #"\roomTemplate.xml");

Categories