Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

c# - Winform Webbrowser being recognized as a mobile device

I'm trying to open websites through the web browser control inside winforms. Although whatever websites it does open, it opens through the mobile version. My web browser is being recognizeed as a mobile device.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can navigate to the page using Navigate method and pass a suitable User-Agent string as additionalHeaders parameter.

The trick is useful for sites which detect mobile mode at server-side based on user-agent string. For some sites which doesn't detect mobile mode and only have client-side responsive design which is based on browser size, you can resize the browser control to a suitable size to show mobile view.

Example

Here is an example of user agent string of Edge on Windows Phone 10.
You may want to use different user agent.

var additionalHeaders = "User-Agent:Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; " +
    "Microsoft; Lumia 950 XL Dual SIM) AppleWebKit/537.36 (KHTML, like Gecko) " +
    "Chrome/52.0.2743.116 Mobile Safari/537.36 Edge/15.15063
";

this.webBrowser1.Navigate("http://www.stackoverflow.com", null, null, additionalHeaders);

As result you see stackoverflow site in mobile mode:

enter image description here

Note - As a better option, Set the user agent for all subsequent requests

As an option, to set the user agent for all the subsequent requests you can use the following code:

[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(int dwOption, string pBuffer,
    int dwBufferLength, int dwReserved);
const int URLMON_OPTION_USERAGENT = 0x10000001;

string additionalHeaders = "User-Agent:Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; " +
    "Microsoft; Lumia 950 XL Dual SIM) AppleWebKit/537.36 (KHTML, like Gecko) " +
    "Chrome/52.0.2743.116 Mobile Safari/537.36 Edge/15.15063
";
private void Form1_Load(object sender, EventArgs e)
{
    UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, 
        additionalHeaders, additionalHeaders.Length, 0);
    webBrowser1.Navigate("http://google.com");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...